如何在C#中使用Enumarable反转一系列元素? [英] How to get reverse of a series of elements using Enumarable in C#?
本文介绍了如何在C#中使用Enumarable反转一系列元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个像
int Max = 10;
int limit = 5;
和字典
Dictionary<String , String> MyDict = new Dictionary<string,string>();
我需要用Max
个元素填充字典,如果索引大于或等于limit
,则该值应该为空.
I need to fill the dictionary with Max
elements and if the index is greater than or equal to limit
then the value should be none.
这是我的示例代码,可以清除我的问题
Here is my sample code which will clear my question
int j = 1;
for (int i = Max-1; i >= 0; i--)
{
if (i >= limit)
MyDict.Add((j++).ToString(), "None");
else
MyDict.Add((j++).ToString(), i.ToString());
}
所以结果会像
{ "1" "None" }
{ "2" "None" }
{ "3" "None" }
{ "4" "None" }
{ "5" "None" }
{ "6" "4" }
{ "7" "3" }
{ "8" "2" }
{ "9" "1" }
{ "10" "0" }
如何使用LINQ
或LAMBDA Expression
可以使用Enumarable
来完成相反的操作
The reverse can be done using Enumarable
here it is
MyDict = Enumerable.Range(0, Max)
.ToDictionary(X => (X + 1).ToString(), X => X >= limit ? "None" : X.ToString());
此表达式的输出
{ "1" "0" }
{ "2" "1" }
{ "3" "2" }
{ "4" "3" }
{ "5" "4" }
{ "6" "None" }
{ "7" "None" }
{ "8" "None" }
{ "9" "None" }
{ "10" "None" }
但是该如何做相反的操作(例如for
循环的输出)呢?或者如何修改现有的LINQ
?
But how to do the reverse of this (like the output of the for
loop)? Or how can I modify the existing LINQ
?
谢谢.
推荐答案
Enumerable.Range(0, Max).OrderByDescending(x => x).ToDictionary(x => (Max - x).ToString(), x => x >= limit ? "None" : x.ToString());
这篇关于如何在C#中使用Enumarable反转一系列元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文