Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Sort A List Of Lists?

Tags:

c#

list

linq

I have a list of lists that I would like to sort.

    foreach (var Row in Result)
    {
        foreach (var RowAll in Row.All)
        {
            DataObject.Add(new List<string>() { RowAll.Value1, RowAll.Value2, RowAll.Value3});
            break; 
        }
    }

Now I want to sort the parent list by each child list's Value2. Is this possible? If so, how can I do this?

like image 512
sooprise Avatar asked Jun 23 '10 17:06

sooprise


2 Answers

You can do this via LINQ:

 // I'm assuming here that "LastCheckin" is defined as List<List<string>> or similar
 // ...

 var sorted = Data.LastCheckin.OrderBy(list => list[1]);

This will return an IEnumerable<List<string>> containing your "lists" sorted by the second value in the sub-list (Value2).


If you want to sort the list in place, you could use List<T>.Sort instead:

 Data.LastCheckin.Sort( (a,b) => a[1].CompareTo(b[1]) );

If you need to specify, at runtime, ascending or decending, an easy way to handle this is:

 bool ascending = true; // Set to false for decending

 int mult = ascending ? 1 : -1;
 Data.LastCheckin.Sort( (a,b) => mult * a[1].CompareTo(b[1]) );

In order to handle more complex checking, you can split your lambda over multiple lines:

 bool ascending = true; // Set to false for decending
 string myDateFormat = GetDateFormat(); // Specify date format

 int mult = ascending ? 1 : -1;
 Data.LastCheckin.Sort( (aStr,bStr) => 
    {
        DateTime a, b;
        bool aSuccess = DateTime.TryParseExact(aStr[1], myDateFormat, DateTimeStyles.None, CultureInfo.InvariantCulture, out a);
        bool bSuccess = DateTime.TryParseExact(bStr[1], myDateFormat, DateTimeStyles.None, CultureInfo.InvariantCulture, out b);

        int result;
        if (!aSuccess)
            result = bSuccess ? -1 : 0;
        else if (!bSuccess)
            result = 1;
        else
            result = a.CompareTo(b);

        return mult * result;

    });

This handles parser failures on a and b, and should put them at the end of the sort.

like image 186
Reed Copsey Avatar answered Oct 02 '22 14:10

Reed Copsey


I managed to get this working:

listOfLists = listOfLists.OrderByDescending(a => a.Max(x => x.paramToSoryBy)).ToList();
like image 29
user787262 Avatar answered Oct 02 '22 14:10

user787262