Basically Sort() method of List<T> is
used to sort the elements in a list but we need to sort a list of list
elements.
Here is an
example, we have a list of routes collection, and these should be sorted by
distance.
Listint>> forwards = new Listint>> {
new List<int>{1, 3000}, new List<int>{2, 5000}, new List<int>{3, 4000}, new List<int>{4, 10000}
};
If we try to sort this list by using simply use the Sort() method of List<T> Type
forwards.Sort();
It throws below
System.InvalidOperationException: 'Failed to
compare two elements in the array.'
System.InvalidOperationException:
'Failed to compare two elements in the array.'
System.InvalidOperationException
HResult=0x80131509
Message=Failed to compare two elements in the
array.
Source=mscorlib
StackTrace:
at System.Collections.Generic.ArraySortHelper`1.Sort(T[]
keys, Int32 index, Int32 length, IComparer`1 comparer)
at System.Array.Sort[T](T[] array, Int32
index, Int32 length, IComparer`1 comparer)
at
System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1
comparer)
at System.Collections.Generic.List`1.Sort()
at Sample.JobT.Main() in
C:\Users\rtiwari\source\repos\PDFSharp_Merge\Sample\Program.cs:line 238
Inner Exception 1:
ArgumentException: At
least one object must implement IComparable.
In
this scenario, we need to define Own IComparer Interface
implemented class
class Comparer : IComparer
- <int>>
{
public int Compare(List<int> x, List<int> y)
{
if (x == null || y == null)
{
return 0;
}
// "CompareTo()" method
return x[1].CompareTo(y[1]);
}
}
Now the Sort() method
is used to sort the elements in the entire List using the specified
comparer – Comparer
forwards.Sort(new Comparer());
Here
is a completed example
public static void Main()
{
List<List<int>>
forwards = new List<List<int>>
{
new List<int>{1,
3000}, new List<int>{2, 5000}, new List<int>{3, 4000}, new List<int>{4,
10000}
};
foreach (var item in forwards)
{
string t = $"[{item[0]}, {item[1]}], ";
Console.Write(t);
}
Console.WriteLine();
Console.WriteLine("After Sorting");
forwards.Sort(new Comparer());
foreach (var item in forwards)
{
string t = $"[{item[0]}, {item[1]}], ";
Console.Write(t);
}
}
Console Output:
Here is a list of the
collections of routes sorted by distance.
No comments:
Post a Comment