开发者

linq null parameter

how can i do the code

     static string BuildMenu(List<Menu> menu, int? parentId)
        {
            foreach (var item in menu.Where(i => i.ParentMenu == parentId || i.ParentMenu.MenuId == parentId).ToList())
            {
            }

        }

return BuildMenu(menuList,null);

so if parentId==null then return only records i => i.ParentMenu == null 开发者_开发问答but when parentId is >0 then return records with i.ParentMenu.MenuId == parentId


You could do that in a single statement, probably something like this

var query = from menu in menus
            where (parentId == null ? menu.ParentMenu == null : menu.ParentMenu != null && menu.ParentMenu.MenuId == parentId)
            select menu;

But I think it would be more readable by breaking it up like the following

var query = menus.AsEnumerable();
if (parentId.HasValue)
    query = query.Where(m => m.ParentMenu != null && m.ParentMenu.MenuId == parentId);
else
    query = query.Where(m => m.ParentMenu == null);

Full example:

public class Menu
{
    public Menu ParentMenu { get; set; }
    public int MenuId { get; set; }
}

...

static void Main(string[] args)
{
    List<Menu> menus = new List<Menu>();
    for (int i = 0; i < 4; i++)
    {
        menus.Add(new Menu() { MenuId = i });
    }

    menus[2].ParentMenu = menus[0];
    menus[3].ParentMenu = menus[1];

    Console.WriteLine(BuildMenu(menus, 1));
    Console.Read();
}

static string BuildMenu(List<Menu> menus, int? parentId)
{
    var query = menus.AsEnumerable();
    if (parentId.HasValue)
        query = query.Where(m => m.ParentMenu != null && m.ParentMenu.MenuId == parentId);
    else
        query = query.Where(m => m.ParentMenu == null);

    StringBuilder builder = new StringBuilder();
    foreach (Menu menu in query)
    {
        // build your string 
        builder.Append(menu.MenuId + ";");
    }

    return builder.ToString();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜