How to get reverse of a series of elements using Enumarable in C#?

点点圈 提交于 2020-01-06 03:20:07

问题


I have two Integer variables 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.


回答1:


Enumerable.Range(0, Max).OrderByDescending(x => x).ToDictionary(x => (Max - x).ToString(), x => x >= limit ? "None" : x.ToString());


来源:https://stackoverflow.com/questions/4123274/how-to-get-reverse-of-a-series-of-elements-using-enumarable-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!