Search code examples
c#linqdictionarykeyvaluepair

Cast A Dictionary after a select to a KeyValue Pair


So I have A dictionary (Employees2Name) Of int => (some class) which I need to turn into a sorted list of key value pairs of int => (some property in the class)

I have this working fine which is the good news. It just seems like I'm doing an extra step is there a way to shorten this in linq with a cast.

ComboBoxValues.Employees2Name.Select(k => new {Key = k.Key, Value = k.Value.Name})
                             .ToDictionary(k => k.Key, v => v.Value)
                             .ToList<KeyValuePair<int, string>>()
                             .OrderBy(kp => kp.Value)

The second to dictionary seems redundant.


Solution

  • @Servy Comments reflects the best answer.

    You already have this in an
    IEnumerable<KeyPairValue<int, Class>> you just need to put the name to a dictionary then order by

    @Html.PopulateCombobox(ComboBoxValues.Employees2Name
                                         .ToDictionary(k => k, v => v.Value.Name)
                                         .OrderBy(v => v.Value)