使用 LINQ 获取序列的奇数/偶数部分 [英] Getting odd/even part of a sequence with LINQ

查看:39
本文介绍了使用 LINQ 获取序列的奇数/偶数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含所有 Projects 的列表,并且我按 Category 将它们分组,如下所示:

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,然后创建右侧 div.我按每个 Category 中的 Projects 数量排序,以在顶部显示 Categories 和最多的 Projects - 因此我想将 projectsByCat 一分为二——如果我把所有奇数"Categories 放在左边,偶数"类别放在右边,我想我将获得合理理智的看法.

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:

用于查询运算符Where"的不受支持的重载.

Unsupported overload used for query operator 'Where'.

而且我认为我是安全的,因为它首先编译..;)

And I thought I was safe since it compiled in the first place.. ;)

有没有一种优雅的方法来做到这一点?而且,对于为什么我对 Where() 的创造性使用不起作用,是否有一个优雅的解释?

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 to Entities,您应该首先将结果完全物化到内存中:

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 框架不会这样做.

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.

这篇关于使用 LINQ 获取序列的奇数/偶数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆