Getting odd/even part of a sequence with LINQ

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);

The oddCategories and the evenCategories are backward.

Indexes start a 0 not 1

0 % 2 = 0

0 index is odd.

var oddCategories  = projectsByCat.Where((cat, index) => index % 2 == 0);

var evenCategories = projectsByCat.Where((cat, index) => index % 2 != 0);

If you're using LINQ to SQL or LINQ to Entities you should first fully materialize the results into memory:

var oddCategories  = projectsByCat.ToList().Where((c,i) => i % 2 != 0);
var evenCategories = projectsByCat.ToList().Where((c,i) => i % 2 == 0);

It isn't possible to iterate through results on the database with an indexer without the use of a cursor, which either ORM framework does not do.

Tags:

C#

Linq