简体   繁体   中英

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 clusters 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.

使用LINQ OrderBy:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM