3

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.

0

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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());

1 Comment

Thank you, in the question I requested sorting based on the first item of each list of string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.