Reputation: 33
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
Reputation: 21548
Order by the length of the first item in each member list:
var ordered = col.OrderBy(c => c.First().Length);
Or if it should be able to handle empty lists and nulls:
var ordered = col.OrderBy(c => c.FirstOrDefault()?.Length);
Upvotes: 0
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
Reputation: 32068
This should work:
var ordered = col.OrderBy(x => x[0].Length).ToList();
Try it out here.
Upvotes: 5