tags:

views:

1054

answers:

4

Hi,

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

The list got structure like

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

By Sort I'd like to do it according to numbers of blockes (asc/desc)

EDIT

the <list<list<string>> is "items" and I access each list by items[0] each of

these items[xx] is a list which means that I want them to sort the array to

    a|b|c|d|eeee|rere|ewew|
    a|b|c|d|eeee|rere
    a|b|c|d|eeee
+1  A: 
List<List<string>> strings = new List<List<string>>();

// add your strings

strings = new List<List<string>>(from str in strings orderby str.Count select str);

Obviously you can adapt this to fit your scenario, but this should give you the general idea of how to create a list that's sorted by the number of elements within a particular string in another list.

Adam Robinson
+8  A: 

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<List<string>>
{
    #region IComparer<List<string>> Members

    public int Compare( List<string> x, List<string> 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.

tvanfosson
oldList.Sort( (a,b) => a.Count.CompareTo( b.Count ) )-in here, what am I supposed to write instead of a and b?
Skuta
Nothing -- a and b are the place holders for the lambda expression and will be assigned values from the outer list when the comparison is invoked.
tvanfosson
+1  A: 

You can sort using the sort method, by creating your own Compararer or giving it a delegate of type Comparison<T>.

ls.Sort((x, y) => x.Count.CompareTo(y.Count));

Here's an example showing how to compare using a lambda expression.

Edit

A very simple way to reverse the sort is to multiply by negative -1

ls.Sort((x, y) => -1 * x.Count.CompareTo(y.Count));
JoshBerke
this is sorting my list in ASC order, how can I revert it?
Skuta
+2  A: 
List<List<string>> list; // filled elsewhere
list.Sort((x,y) => x.Count.CompareTo(y.Count););
Chris Doggett