Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to sort a sorted list by its value column

i have a generic sorted list "results" with key = some filename and value = boolean.

I would like to sort the list by the boolean entry or value column. does anyone know how i can do this?

Thanks!

like image 490
Grant Avatar asked Aug 09 '09 00:08

Grant


3 Answers

SortedList is optimized so that inertions occur in an ordered fashion, such that enumeration occurs in a sorted order at minimal cost. Anything else requires a re-sort. Thus:

        SortedList<string,bool> l = new SortedList<string, bool>();
        l.Add("a", true);
        l.Add("b", false);
        l.Add("c", true);
        l.Add("d", false);
        var orderByVal = l.OrderBy(kvp => kvp.Value);

but this enumeration will be significantly slower to calculate, and be performed up-front, requiring extra storage to do so.

Depending on your situation it might be cheaper to maintain 2 SortedList instances with the key/value reversed.

like image 105
spender Avatar answered Nov 03 '22 08:11

spender


For descending all list items

list.OrderByDescending(); 

or

var list = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price).ToList();
like image 28
mansoor Avatar answered Nov 03 '22 08:11

mansoor


In .NET 2.0, you could add your items to a SortedList:

  public static List<MyObject> SortedObjects(IEnumerable<MyObject> myList) {
     SortedList<string, MyObject> sortedList = new SortedList<string, MyObject>();
     foreach (MyObject object in myList) {
        sortedList.Add(object.ValueIWantToSort, object);
     }

     return new List<MyObject>(sortedList.Values);
  }
like image 20
C-Pound Guru Avatar answered Nov 03 '22 10:11

C-Pound Guru