I have two Integer variable开发者_Python百科s like
int Max = 10;
int limit = 5;
and a Dictionary
Dictionary<String , String> MyDict = new Dictionary<string,string>();
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());
}
so the result will be like
{ "1" "None" }
{ "2" "None" }
{ "3" "None" }
{ "4" "None" }
{ "5" "None" }
{ "6" "4" }
{ "7" "3" }
{ "8" "2" }
{ "9" "1" }
{ "10" "0" }
How to do this using LINQ or LAMBDA Expression
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());
Output of this expression
{ "1" "0" }
{ "2" "1" }
{ "3" "2" }
{ "4" "3" }
{ "5" "4" }
{ "6" "None" }
{ "7" "None" }
{ "8" "None" }
{ "9" "None" }
{ "10" "None" }
But how to do the reverse of this (like the output of the for loop)? Or how can I modify the existing LINQ?
Thanks in advance.
Enumerable.Range(0, Max).OrderByDescending(x => x).ToDictionary(x => (Max - x).ToString(), x => x >= limit ? "None" : x.ToString());
加载中,请稍侯......
精彩评论