How To Sort a List<T>?
This question already has an answer here:
Your example code will not compile, because the ID
property of your class needs to be an int
instead of a string
and you need to put double quotes around your string values, like this:
public class Checkit
{
public int ID { get; set; }
public string b { get; set; }
public string c { get; set; }
}
List<Checkit> Lst_Ch = new List<Checkit>();
Lst_Ch.Add(new Checkit
{
ID = 123,
b = "afasfa",
c = "afagas"
});
Lst_Ch.Add(new Checkit
{
ID = 124,
b = "afasfa",
c = "afagas"
});
Lst_Ch.Add(new Checkit
{
ID = 523,
b = "afasfa",
c = "afagas"
});
Lst_Ch.Add(new Checkit
{
ID = 123,
b = "afasfa",
c = "afagas"
});
Lst_Ch.Add(new Checkit
{
ID = 523,
b = "afasfa",
c = "afagas"
});
Lst_Ch.Add(new Checkit
{
ID = 105,
b = "afasfa",
c = "afagas"
});
Second, to sort the list, do the following:
IEnumerable<Checkit> query = Lst_Ch.OrderBy(l => l.ID).ToList();
The variable query
is now your sorted list, which you can use elsewhere, loop through, etc.
You can
Use Linq to sort it and create a new List<T>
. Something like:
List<Foo> unsortedList = CreateAnUnorderedList() ;
List<Foo> sortedList = unsortedList.OrderBy( x => x.DateCreated )
.ThenBy( x => x.Id )
.ToList()
;
You can sort it in place. Something like:
List<Foo> myList = CreateAnUnorderedList() ;
myList.Sort( (x,y) => x.Id < y.Id ? -1 : x.Id > y.Id ? +1 : 0 ) ;
Alternatively, you can use an ordered collection, like SortedList<T>
.
上一篇: 在C#中对列表进行排序的方法
下一篇: 如何对列表进行排序<T>?