开发者

How do I sort the following list

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:

  1. 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);
  2. 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);
  3. Using a list of wrappers around clusters that keep track of any of the values mentioned in 1 and 2;
  4. Rolling your own sorting algorithm.


using LINQ OrderBy:

 var orderedClusters = clusters.OrderBy(list => list.Max(item => item.SequenceNo))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜