Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

linq - How to get Alternate elements using Enumerable in C#

This is a continuation of my question: How to get reverse of a series of elements using Enumarable in C#?

Now I need alternate elements only. Here is my solution using for loop:

int Max = 10;
int limit = 5;
Dictionary<String , String> MyDict = new Dictionary<string,string>();
int j = 0;
for (int i = 0; i <Max; i++)
{
    if (i >= limit)
        MyDict.Add((i+1).ToString(), "None");
    else
        MyDict.Add((i+1).ToString(), j.ToString());
    j+=2;
}

The output is like

{ "1" "0"}
{ "2" "2"}
{ "3" "4"}
{ "4" "6"}
{ "5" "8"}
{ "6" "None"}
{ "7" "None"}
{ "8" "None"}
{ "9" "None"}
{ "10" "None"}

How to do this using Enumarerable or Using any LINQ method. And also the reverse like my previous question: How to get reverse of a series of elements using Enumarable in C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...