如何使用C#可枚举来获得替代元素 [英] How to get Alternate elements using Enumerable in C#

查看:227
本文介绍了如何使用C#可枚举来获得替代元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题的延续:的如何在C#中使用Enumarable一系列元素的反向?

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"}

如何使用要做到这一点 Enumarerable 或使用任何LINQ方法。也是反向像我刚才的问题:的如何得到一系列在C#中使用Enumarable?

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

推荐答案

您可以使用标准LINQ 其中,扩展方法,做你所需要的一个基础。

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

由于<$ C $名单C>的IEnumerable< T> 它的工作是这样的:

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.

这篇关于如何使用C#可枚举来获得替代元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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