Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

c# - How to sort a List collection of classes with properties in them?

I have a List of classes in my collection like

List<MyClass> test = new List<MyClass>();

In my classes I have just some properties

public string id {get; set;}
public DateTime date {get; set;}

Now I make these classes by getting some queries from 2 different database tables. I then take those 2 results from the database tables and using a foreach loop I make a new MyClass object and stick it in my "test" collection.

Now once all these classes are put in the the list collection. I want to sort through them and order the classes by the "date" property.

How could I do this? I can't order then right when I get them from the database since I am getting them from 2 different database tables and ordering them separately would only make it ordered in for each section but table one might have 12/12/2009 and so might table two. So they need to be ordered together.

So can I some how use linq or something to order them?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about:

list.Sort((x,y) => DateTime.Compare(x.date, y.date));

which sorts the existing list, or:

var sorted = list.OrderBy(x=>x.date).ToList();

which creates a second list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...