Lirila Mzr
Lirila Mzr

Reputation: 33

Sorting an array of List<string> using linq

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"}

Upvotes: 2

Views: 201

Answers (3)

Stephen Kennedy
Stephen Kennedy

Reputation: 21548

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

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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.

Upvotes: 1

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

This should work:

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

Try it out here.

Upvotes: 5

Related Questions