How To Sort A List Of Lists?

12,200

Solution 1

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.

Solution 2

I managed to get this working:

listOfLists = listOfLists.OrderByDescending(a => a.Max(x => x.paramToSoryBy)).ToList();
Share:
12,200
sooprise
Author by

sooprise

I like to program, but am a noob, which is why I'm here. &lt;-My sexy fatbooth picture

Updated on July 06, 2022

Comments

  • sooprise
    sooprise almost 2 years

    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?