How to sort List> according to List number of fields?

前端 未结 5 667
渐次进展
渐次进展 2021-01-22 15:22

How do I sort List> according to number of fields?

The list got structure like

a|b|c|d|eeee|rere|ewew|
ewqewq|ewew|
ewew|ewewewewew|
<         


        
5条回答
  •  迷失自我
    2021-01-22 16:24

    If you don't need to sort "in place" you can use LINQ to give you a new sorted, list.

    var sorted = oldList.OrderBy( l => l.Count );
    

    Otherwise you'll need to write your own Comparer that takes two lists and returns the ordering by their size.

    public class CountComparer : IComparer>
    {
        #region IComparer> Members
    
        public int Compare( List x, List y )
        {
            return x.Count.CompareTo( y.Count );
        }
    
        #endregion
    }
    
    
    
    oldList.Sort( new CountComparer() );
    

    Or, as @Josh points out, you can do this with a lambda expression.

    oldList.Sort( (a,b) => a.Count.CompareTo( b.Count ) )
    

    IMO this latter works well if the comparison is relatively simple or used once, but the actual class may be preferable as the comparison gets more complex or if you need to repeat it in multiple places.

提交回复
热议问题