Convert an IOrderedEnumerable> into a Dictionary

后端 未结 3 555
花落未央
花落未央 2020-12-29 19:07

I was following the answer to another question, and I got:

// itemCounter is a Dictionary, and I only want to keep
// key/value pairs with         


        
相关标签:
3条回答
  • 2020-12-29 19:47

    You are specifying incorrect generic arguments. You are saying that TSource is string, when in reality it is a KeyValuePair.

    This one is correct:

    sortedDict.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value);
    

    with short version being:

    sortedDict.ToDictionary(pair => pair.Key, pair => pair.Value);
    
    0 讨论(0)
  • 2020-12-29 19:50

    The question is too old but still would like to give answer for reference:

    itemCounter = itemCounter.Take(maxAllowed).OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
    
    0 讨论(0)
  • I believe the cleanest way of doing both together: sorting the dictionary and converting it back to a dictionary would be:

    itemCounter = itemCounter.OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
    
    0 讨论(0)
提交回复
热议问题