How to sort a <list> of class in c#?

12,639

Solution 1

You can use LINQ for it.

Ascending Order

var result = lstCityt.OrderBy(C=> C.CityName).ThenBy(C=> C.Province).ThenBy(C=> C.Code);

Descending Order

var result = lstCityt.OrderByDescending(C=> C.CityName).ThenByDescending(C=> C.Province).ThenByDescending(C=> C.Code);

Both

var result = lstCityt.OrderBy(C=> C.CityName).ThenByDescending(C=> C.Province).ThenByDescending(C=> C.Code);

Solution 2

What you already have is already complete and correct:

lstCityt.Sort((x, y) => string.Compare(x.CityName, y.CityName));

That indeed sorts a list of a class. It sounds like you are seeing some secondary issue to do with the repeater, but you have not provided context for that. The main thing I'd look at is timing, i.e. whether you binding before or after sorting the list.

Share:
12,639
maryam mohammadi
Author by

maryam mohammadi

Updated on June 14, 2022

Comments

  • maryam mohammadi
    maryam mohammadi almost 2 years

    I have a list of a class like this :

     public class CityCodeInfo
     {
        public string CityName;
        public string Province;
        public string Code; 
      }
    
      List<CityCodeInfo> lstCityt = new List<CityCodeInfo>();
    

    How can i sort this list by any of its variables (cityname, province and code)

    i've tried this code:

      lstCityt.Sort((x, y) => string.Compare(x.CityName, y.CityName));
    

    but it doesn't work...

    Any Idea?!

  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 12 years
    Why use LINQ when List<>.Sort is faster, and is what the Original Poster asks for? Your solution does not alter the original List<>, only gives a new IEnumerable<> with the sorted order.
  • maryam mohammadi
    maryam mohammadi almost 12 years
    i test u'r code, but nothing happen. no error, no sorting list. how to work with IEnumerable<>?!
  • Kundan Singh Chouhan
    Kundan Singh Chouhan almost 12 years
    @maryammohammadi result variable contains your sorted data and you can convert this result IEnumerable<> in to List via ToList() method.
  • Kundan Singh Chouhan
    Kundan Singh Chouhan almost 12 years
    @JeppeStigNielsen, in terms to use Sort method the class must implement IComparable or IComparable<T> interface and also write the delegates to sort the elements of list, so i think this would be the simplest solution. For your concern find this article to use sort method with list
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 12 years
    The Original Poster uses an overload of Sort that takes a Comparison<CityCodeInfo> delegate as an argument. Therefore that delegate will be used for the sorting, and in that case CityCodeInfo does not need to implement IComparable.
  • maryam mohammadi
    maryam mohammadi almost 12 years
    @ Kundan Singh Chouhan Thank u very much. it works well. i do appreciate.