2

How do I sort an array of List<string> by length of string using Linq? The efficiency of execution does not matter.

List<string>[] col = new List<string>[]
{
    new List<string>(){"aaa", "bbb"},
    new List<string>(){"a", "b", "d"},
    new List<string>(){"xy","sl","yy","aq"}
}; //Each string in a list of strings of a particular array element has equal length.

After sorting should produce

{"a", "b", "d"}, {"xy","sl","yy","aq"}, {"aaa", "bbb"}

3
  • 1
    col.OrderBy(x => x.Sum(y => y.Length)).ToList(); Commented Feb 14, 2018 at 13:24
  • @RomanKoliada That won't give you the correct result. Commented Feb 14, 2018 at 13:30
  • @Roman Koliada: The given array itself should be sorted so that the structure is maintained in the original array form. Commented Feb 14, 2018 at 14:00

3 Answers 3

5

This should work:

var ordered = col.OrderBy(x => x[0].Length).ToList();

Try it out here.

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

Comments

1

If you want to sort out existing col list (i.e. in place sorting):

col.Sort((left, right) = > left[0].Length.CompareTo(right[0].Length));

It's not Linq, however.

Comments

0

Order by the length of the first item in each member list:

var ordered = col.OrderBy(c => c.First().Length);

Fiddle


Or if it should be able to handle empty lists and nulls:

var ordered = col.OrderBy(c => c.FirstOrDefault()?.Length);

Fiddle

Comments

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.