I have a list called clusters and in that list there is another list called tags which has a sequenceno.
How do I sort c开发者_JAVA百科lusters by using the max of seuqenceno from tags of each cluster using lambda expression in one line.
Something like
clusters.Sort((a,b) => a.tags......
A not very efficient solution (computes O(N log N) maximums, but runs in-place):
clusters.Sort((a,b) => a.tags.Max(x => x.sequenceno)
.CompareTo(b.tags.Max(x => x.sequenceno)));
A somewhat better solution (only computes O(N) maximums, but does not work in-place):
var max = clusters.ConvertAll(c => c.tags.Max(x => x.sequenceno);
clusters = clusters.Select((x,i) => new{x,i})
.OrderBy(xi => max[xi.i].CompareTo(max[xi.j]))
.Select(xi => xi.x)
.ToList();
It will be difficult to do this sort efficiently in-place without either:
- Adding a property to the cluster class to cache the maximum sequence number of the tags (and handle its possible invalidation, which can get tricky);
- Adding a property to the cluster class to keep track of its index (which may not make sense in there, and may raise invalidation issues as well);
- Using a list of wrappers around clusters that keep track of any of the values mentioned in 1 and 2;
- Rolling your own sorting algorithm.
using LINQ OrderBy:
var orderedClusters = clusters.OrderBy(list => list.Max(item => item.SequenceNo))
精彩评论