Home > Enterprise >  Order Dictionary by the result of other dictionary
Order Dictionary by the result of other dictionary

Time:12-14

Looking for someone to help me with C#, LINQ.

I have a Dictionary<int,int> that I am ordering like so: .OrderBy(_ => _.Value).ThenBy(_ => ThisMethodReturnsAnotherIReadOnlyDict<int,int>()).ThenByDescending(_ => _.Key).

What I want is to order the first dictionary by its value and then if there are still equal values I want that tie to be broke by the ThisMethodReturnsAnotherIReadOnlyDict<int,int>(). This first key/value of this ThisMethodReturnsAnotherIReadOnlyDict to break the tie and be on top. And finally, if everything fails, then order by it's key descending.

Some data for this like:

(First Dictionary)

[1,400]
[2,550]
[3,200]
[4,200]

(Second dictionary)

[3,50]
[4,140]
[2,600]
[1,700]

For this scenario I want my ordering to return: [3,50]

Can anyone help please? Thanks!

CodePudding user response:

It looks like you're looking for something like this:

var firstDict = new Dictionary<int, int>() {
    {1,400}, 
    {2,550},
    {3,200},
    {4,200}
};

var secondDict = new Dictionary<int, int>() {
    {3,50}, 
    {4,140},
    {2,600},
    {1,700}
};

var result = (from kvp in firstDict
             join tieBreaker in secondDict on kvp.Key equals tieBreaker.Key
             select new { kvp.Key, V1 = kvp.Value, V2 = tieBreaker.Value })
                .OrderBy(x => x.V1)
                .ThenBy(x => x.V2)
                .ThenByDescending(x => x.Key)
                .First();

This will join the first and second dictionaries together by its keys and will, respectively, order by the value of the first dictionary, the value of the second dictionary and then descending by the key itself.

CodePudding user response:

How about:

var ans = firstDict
    .OrderBy(kv => kv.Value)
    .ThenBy(kv => ThisMethodReturnsAnotherIReadOnlyDict<int,int>().TryGetValue(kv.Key, out var val2) ? val2 : kv.Key)
    .ToList();

Unless ThisMethodReturnsAnotherIReadOnlyDict<int,int> may change, you may want to cache the return value in a variable before sorting.

  • Related