Getting odd/even part of a sequence with LINQ

前端 未结 7 1305
再見小時候
再見小時候 2020-12-01 06:47

Say I have a list of all Projects, and that I group them by Category like this:

var projectsByCat = from p in Projects
                     


        
7条回答
  •  温柔的废话
    2020-12-01 07:15

    Note that calling .ToList() twice for the same query is going query the database twice.

    It would be much better to cache the result in an intermediate list, then apply your predicate filtering:

    var projectsByCat =
        (from p in Projects
        group p by p.Category into g
        orderby g.Count() descending
        select new { Category = g.Key, Projects = g }).ToList();
    
    var oddCategories = projectsByCat.Where((cat, index) => index % 2 != 0);
    var evenCategories = projectsByCat.Where((cat, index) => index % 2 == 0);
    

提交回复
热议问题