Sorting a SortedDictionary based on value, not key

后端 未结 4 572
猫巷女王i
猫巷女王i 2021-01-18 18:11

I have a SortedDictionary, the key is a int value and the matching value to each key is a class object. The class contains a int and a two datetime variable.

I need

相关标签:
4条回答
  • 2021-01-18 18:53

    You could use a Linq query.

    var D = new SortedDictionary<int, string>();
    var qD = from kvp in D
             orderby kvp.Value
             select kvp
    ;
    
    0 讨论(0)
  • 2021-01-18 19:08

    I think you can use SortedSet and Tuple of your key and value, like: SortedSet> ((a,b)=>(a.Item2.CompareTo(b.Item2));

    0 讨论(0)
  • 2021-01-18 19:14

    SortedDictionary can't be sorted by value, though you can extract a sorted list of values, as the other answers point out.

    What you want to do is use a list of keyvaluepairs instead, then sort that, like so:

    List<KeyValuePair<int, BusDetail>> busses = GetMyListOfBusses();
    busses.Sort((first, next) => { 
         return first.Value.InTime.CompareTo(next.Value.Intime); 
    });
    

    At that point, your keyvaluepair list of busses will be sorted by InTime

    0 讨论(0)
  • 2021-01-18 19:16

    Sorted Dictionary will always sort on the key, so there is no way to re-arrange it's data so they are sorted on anything other that the key. What you can do is get the data into another structure (some kind of IOrderedEnumerable) where they can be sorted on things other that the key.

    If you want to discard the keys and just get the values then

    var sortedValues = dictionary.Values.OrderBy(busDetail => busDetail.InTime);
    

    will work, and the type of sortedValues will be IOrderedEnumerable<BusDetail>. If you still need to keep both the keys and values, you could do:

    var sortedElements = dictionary.OrderBy(kvp => kvp.Value.InTime);
    

    which will return a IOrderedEnumerable<KeyValuePair<int, BusDetail>>. You can that foreach on any of these two collections, or you could bind them to a grid's datasource.

    0 讨论(0)
提交回复
热议问题