How can I sort List<T> based on properties of T?
Asked Answered
U

4

15

My Code looks like this :

Collection<NameValueCollection> optionInfoCollection = ....
List<NameValueCollection> optionInfoList = new List<NameValueCollection>();
optionInfoList = optionInfoCollection.ToList();

if(_isAlphabeticalSoting)
   Sort optionInfoList

I tried optionInfoList.Sort() but it is not working.

Uttasta answered 3/3, 2009 at 5:20 Comment(0)
C
26

Using the sort method and lambda expressions, it is really easy.

myList.Sort((a, b) => String.Compare(a.Name, b.Name))

The above example shows how to sort by the Name property of your object type, assuming Name is of type string.

Compressed answered 3/3, 2009 at 5:38 Comment(2)
You could just use string.Compare(a.Name, b.Name), which would be safe?Chon
Thanks! Learn something new everyday... I'll edit the answer.Compressed
C
8

If you just want Sort() to work, then you'll need to implement IComparable or IComparable<T> in the class.

If you don't mind creating a new list, you can use the OrderBy/ToList LINQ extension methods. If you want to sort the existing list with simpler syntax, you can add a few extension methods, enabling:

list.Sort(item => item.Name);

For example:

public static void Sort<TSource, TValue>(
    this List<TSource> source,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    source.Sort((x, y) => comparer.Compare(selector(x), selector(y)));
}
public  static void SortDescending<TSource, TValue>(
    this List<TSource> source,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    source.Sort((x, y) => comparer.Compare(selector(y), selector(x)));
}
Chon answered 3/3, 2009 at 5:43 Comment(1)
Do you have an example of using these extension methods, I tried using for my question #31057758, but couldn't implement the way you have suggestedCoussoule
C
2
public class Person  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

List<Person> people = new List<Person>();

people.Sort(
    delegate(Person x, Person y) {
        if (x == null) {
            if (y == null) { return 0; }
            return -1;
        }
        if (y == null) { return 0; }
        return x.FirstName.CompareTo(y.FirstName);
    }
);
Camarilla answered 21/9, 2011 at 19:26 Comment(0)
T
1

You need to set up a comparer that tells Sort() how to arrange the items.

Check out List.Sort Method (IComparer) for an example of how to do this...

Thermolysis answered 3/3, 2009 at 5:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.