How to get Alternate elements using Enumerable in

2019-01-29 02:38发布

问题:

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#?

回答1:

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.



回答2:

int max = 10;
int limit = 5;

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


回答3:

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.