Reputation: 9678
I have a list of lists of string
List<string> l1 = new List<string>();
l1.Add("i");
l1.Add("k");
List<string> l2 = new List<string>();
l2.Add("f");
l2.Add("a");
pChain = new List<List<string>>();
pChain.Add(l1);
pChain.Add(l2);
...
I want to sort pChain
based on the first item of each list (the result should be l2, l1).
I tried pChain.Sort();
but an exception occurs
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: Failed to compare two elements in the array.
Upvotes: 3
Views: 9648
Reputation: 30052
The default call to pChain.Sort()
can't predict that you want to sort by the first element, you need to explicity specify that:
pChain.Sort((x, y) => String.Compare(x.FirstOrDefault(), y.FirstOrDefault()));
Alternatively you can use Linq's OrderBy (which is a stable sort as per the documentation):
pChain = pChain.OrderBy( x => x.FirstOrDefault()).ToList();
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.
Upvotes: 13
Reputation: 37281
You get that error because C# can't know how to sort an item of pChain
for you because it is an IEnumerable
of its own.
Would you want to sort it by the Max
items? Or by Count
of items?.. Or many others
You should supply some rule for it to compare by like an IComparable<List<string>>
or:
pChain = pChain.OrderBy(item => item.FirstOrDefault());
Upvotes: 7