C# 使用 LINQ 获取序列的奇数/偶数部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/267033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:32:38  来源:igfitidea点击:

Getting odd/even part of a sequence with LINQ

c#linq

提问by Rune Jacobsen

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

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

var projectsByCat = from p in Projects
                    group p by p.Category into g
                    orderby g.Count() descending
                    select new { Category = g.Key, Projects = g };

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 Projectsin each Categoryto show the Categorieswith the most Projectson top - thus I would like to split projectsByCatin two - if I put all the "odd numbered" Categorieson the left and the "even numbered" categories on the right, I think I will get a reasonably sane view.

现在我想将其显示为网页中的列表,首先我创建左侧 div,其次创建右侧 div。我订购的数量Projects在各个Category展现CategoriesProjects顶部-因此,我想分projectsByCat两个-如果我把所有的“奇数”Categories左边和“偶数”类别上的权利,我我想我会得到一个合理理智的看法。

So I thought I could do this to get the odd and even members of projectsByCat:

所以我想我可以这样做以获得奇数和偶数成员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'.

用于查询运算符“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?

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

Thanks in advance!

提前致谢!

采纳答案by Mark Cidade

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

如果您使用 LINQ to SQL 或 LINQ to Entities,您应该首先将结果完全物化到内存中:

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 notdo.

这是不可能的迭代通过与不使用游标,无论是ORM框架没有一个索引数据库的结果没有做。

回答by Jacob Carpenter

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

请注意,.ToList()为同一查询调用两次将查询数据库两次。

It would be much better to cache the result in an intermediate list, thenapply 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);

回答by bjhamltn

The oddCategories and the evenCategories are backward.

oddCategories 和 evenCategories 是落后的。

Indexes start a 0 not 1

索引从 0 开始,而不是 1

0 % 2 = 0

0 % 2 = 0

0 index is odd.

0 索引是奇数。

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

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

回答by Lasse V. Karlsen

The proper way to do this using LINQ, and avoiding multiple enumerations over the input, is to do a grouping or similar on whether each item is even or odd.

使用 LINQ 执行此操作并避免对输入进行多次枚举的正确方法是对每个项目是偶数还是奇数进行分组或类似操作。

A simple way using the overload for Selectthat mixes in an indexcoupled with ToLookupgives you what you want:

一个简单的方法Select在索引混合使用重载,ToLookup给你你想要的:

var oddsAndEvens = input
    .ToList() // if necessary to get from IQueryable to IEnumerable
    .Select((item, index) => new { isEven = index % 2 != 0, item })
    .ToLookup(
        i => i.isEven,
        i => i.item);

This will produce a Lookup<TKey, TElement>data structure that has the following benefit:

这将产生Lookup<TKey, TElement>具有以下优点的数据结构:

If the key is not found in the collection, an empty sequence is returned.

如果在集合中找不到该键,则返回一个空序列。

This means that after the above LINQ query you can do:

这意味着在上述 LINQ 查询之后,您可以执行以下操作:

var evens = oddsAndEvens[true];
var odds = oddsAndEvens[false];

回答by Athul Nalupurakkal

You can separate odd and even in your view using linq.

您可以使用 linq 在视图中分离奇数和偶数。

//even 
@foreach (var item in Model.Where((item, index) => index % 2 == 0))
{
     //do the code
}

//odd
@foreach (var item in Model.Where((item, index) => index % 2 != 0))
{
     //do the code
}

回答by Sam Saarian

var text = "this is a test <string> to extract odd <index> values after split";
var parts = text.Split(new char[] { '<', '>' });
IEnumerable words = parts.Where(x => parts.ToList().IndexOf(x) % 2 == 1)

wordswould contain "string" and "index"

单词将包含“字符串”和“索引”

回答by Hrishikesh Kulkarni

You Can find Even odd number without foreach loop

您可以在没有 foreach 循环的情况下找到偶数奇数

static void Main(string[] args)
{
    List<int> lstnum = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    List<int> lstresult = lstnum.FindAll(x => (x % 2) == 0);

    lstresult.ForEach(x => Console.WriteLine(x));
}