Home > Software engineering >  How to sort a list of keyvaluepairs with some operations involved
How to sort a list of keyvaluepairs with some operations involved

Time:10-25

As much as there are similar questions here in stack overflow, there is just something about this problem that my solution won't work. I have a given number,

For example: int target = 15

Then a list of keyvaluepairs,

var farm = new List<KeyValuePair<string,int>>()
{
   new KeyValuePair<string,int>("apple", 25),
   new KeyValuePair<string,int>("veges", 35),
   new KeyValuePair<string,int>("watermelon", 0),
   new KeyValuePair<string,int>("grapes", 10),
}

Now I want to sort the list based on the difference of the given number which is 15 and the second element in the list of pairs.

Here's my solution so far but it didn't make any changes:

farm.Sort((prod1, prod2) => Math.Abs(prod1.Value - target) < Math.Abs(prod2 - target) 
                                   ? prod1.Value : prod2.Value)

Expected sort should be:

("grapes", 10)      // |10-15| = 5
("apple", 25)       // |25-15| = 10
("watermelon", 0)  // |0-15| = 15
("veges", 35)       // |35-15| = 20

Any insight would be very much appreciated.

CodePudding user response:

The overload of List<T>.Sort you are using accepts the delegate Comparison<T>.

From the docs, for arguments x and y, the return value indicates the following:

Value Meaning
Less than 0 x is less than y
0 x equals y
Greater than 0 x is greater than y

Currently you are simply returning the Value property of the lesser argument, which has no relevance to the above criteria.

You are also not accounting for the scenario where prod1 and prod2 are equal.

The simplest solution is to subtract one from the other:

farm.Sort(
    (prod1, prod2) => Math.Abs(prod1.Value - target) - Math.Abs(prod2 - target));

Or you could use int.CompareTo which does the same:

farm.Sort(
    (prod1, prod2) => Math.Abs(prod1.Value - target)
        .CompareTo(Math.Abs(prod2 - target)));

CodePudding user response:

Try this way:

        int target = 15;
        var farm = new List<KeyValuePair<string, int>>()
        {
            new KeyValuePair<string, int>("apple", 25),
            new KeyValuePair<string, int>("veges", 30),
            new KeyValuePair<string, int>("watermelon", 35),
            new KeyValuePair<string, int>("grapes", 10),
        };
        farm.Sort((prod1, prod2) => Math.Abs(prod1.Value - target).CompareTo(Math.Abs(prod2.Value - target)));
  • Related