c# - Sort Dictionary based on values in a list of integers -


I'm having trouble sorting a dictionary based on the sum of 1s in the list of integers inside the same dictionary, so first I want to count 1s in each list and then sort the dictionary based on the result. I have found some solutions in StackVareflow but they do not answer my question.

The dictionary looks like the following:

  dictionary & lt; Int, list & lt; Int & gt; & Gt; ; MyDic = New Dictionary & lt; Int, list & lt; Int & gt; & Gt; (); & Lt; Integer & gt; MyList = new list & lt; Int & gt; (); MyList = new list & lt; Int & gt; (); // The third myList should show. Add (0); MyList.Add (0); MyList.Add (1); MyDic.Add (0, myList); MyList = new list & lt; Int & gt; (); // second myList.Add (1); MyList.Add (1); MyList.Add (0); MyDic.Add (1, myList); MyList = new list & lt; Int & gt; (); // should show my list first Add (1); MyList.Add (1); MyList.Add (1); MyDic.Add (2, myList);  

I tried this code but it seems that it does nothing.

  list & lt; Keyvaluepair & lt; Int, list & gt; Int & gt; & Gt; & Gt; MyList2 = myDic.ToList (); MyList2.Sort ((FirstPear, Next Peer) => {First Return Pair.Value.Where (i => I == 1) .Sum (). Compare (Next Pair.Value.Where (x = & Gt; x == 1) .Sum ());});  

You are sorting list items in ascending order. To wit. Items with more than 1 will go to the end of the list. You should use descending order. Simply compare the next comparison text of the pie (or the change symbol of the result of comparison):

  myList2.Sort ((firstpires, next peer) => {next peer value, where (i = & Gt; i = = 1) .Sum () Compare (FirstPier.WWWhere (x => x == 1) .Sum ());});  

There is a problem in this approach - the sum of 1s in value is compared to two objects each time. Better use enumerable.orderbodsensing . It is easier to use, and it will calculate comparison values ​​(such as) only once. Thus, the dictionary key is a calculator of the Viewpoint, you can use commands with the words, respectively:

  var result = myDic.OrderByDescending (kvp = & gt; kvp.Value.Where ( I = & gt; i == 1) .sum ());  

Comments

Popular posts from this blog

Member with no value in F# -

java - Joda Time Interval Not returning what I expect -

c# - Showing a SelectedItem's Property -