获得奇/偶与LINQ序列的一部分 [英] Getting odd/even part of a sequence with LINQ
问题描述
说我有所有的项目
的名单,而我组他们通过类别
是这样的:
Say I have a list of all Projects
, and that I group them by Category
like this:
var projectsByCat = from p in Projects
group p by p.Category into g
orderby g.Count() descending
select new { Category = g.Key, Projects = g };
现在我想显示这是一个网页列表,其中第一个创建左侧DIV,其次右侧股利。我对中的每个
显示类别项目
的数量订购类别
最项目
之上 - 所以我想分裂 projectsByCat
两种 - 如果我把所有在奇数类别
左侧和偶数关于正确分类,我想我会得到一个合理健全的看法。
Now I want to display this as a list in a web page, where first I create the left side div, secondly the right side div. I am ordering by number of Projects
in each Category
to show the Categories
with the most Projects
on top - thus I would like to split projectsByCat
in two - if I put all the "odd numbered" Categories
on the left and the "even numbered" categories on the right, I think I will get a reasonably sane view.
所以我想我能做到这一点获得的奇数和偶数成员 projectsByCat
:
So I thought I could do this to get the odd and even members of projectsByCat
:
var oddCategories = projectsByCat.Where((cat, index) => index % 2 != 0);
var evenCategories = projectsByCat.Where((cat, index) => index % 2 == 0);
和它编译 - 但是,当我运行它,我得到一个异常,如这样的:
And it compiles - however, when I run it, I get an exception such as this:
用于查询运营商不支持重载'在哪里'。
Unsupported overload used for query operator 'Where'.
和我想我是安全的,因为它摆在首位编译..;)
And I thought I was safe since it compiled in the first place.. ;)
有一种优雅的方式来做到这一点?而且,有一个优雅的解释,为什么我的创作使用其中()
将无法正常工作?
Is there an elegant way to do this? And also, is there an elegant explanation for why my creative use of Where()
won't work?
在此先感谢!
推荐答案
如果你使用LINQ to SQL或LINQ到实体应首先完全实现结果到内存:
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);
这是不可能通过与索引数据库的结果,而不使用游标,这无论是ORM框架做的不可以做的。
这篇关于获得奇/偶与LINQ序列的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!