How to get Alternate elements using Enumerable in C#

£可爱£侵袭症+ 提交于 2019-11-29 17:06:16

You could use the standard LINQ Where extension method as a basis for doing what you need.

Given a list of IEnumerable<T> it would work like this:

var evens = list.Where((t, i) => i % 2 == 0);
var odds = list.Where((t, i) => i % 2 == 1);

Hopefully you can build on these to do what you want.

int max = 10;
int limit = 5;

var dict = Enumerable.Range(1, max)
                     .ToDictionary(x => x.ToString(),
                                   x => (x > limit) ? "None"
                                                    : ((x - 1) * 2).ToString());

I don't think there is a standard LINQ method that does this. But you can create custom IEnumerable extension methods to do this sort of thing.

http://msdn.microsoft.com/en-us/library/cc981895.aspx

Alternate elements is one of the examples here. Basically it's just taking your example code and packaging it as an extension so you get the syntax you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!