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.
Author by
maryam mohammadi
Updated on June 14, 2022Comments
-
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 almost 12 yearsWhy use LINQ when
List<>.Sort
is faster, and is what the Original Poster asks for? Your solution does not alter the originalList<>
, only gives a newIEnumerable<>
with the sorted order. -
maryam mohammadi almost 12 yearsi test u'r code, but nothing happen. no error, no sorting list. how to work with IEnumerable<>?!
-
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 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 almost 12 yearsThe Original Poster uses an overload of
Sort
that takes aComparison<CityCodeInfo>
delegate as an argument. Therefore that delegate will be used for the sorting, and in that caseCityCodeInfo
does not need to implementIComparable
. -
maryam mohammadi almost 12 years@ Kundan Singh Chouhan Thank u very much. it works well. i do appreciate.