Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

asp.net

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?!

like image 556
maryam mohammadi Avatar asked Nov 23 '25 16:11

maryam mohammadi


1 Answers

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);
like image 169
Kundan Singh Chouhan Avatar answered Nov 25 '25 05:11

Kundan Singh Chouhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!