问题
I have a record class like this :
public class RecordInfo
{
public String CDate;
public String Patient_ID;
public Color Zone;
public String Fname;
public String Lname;
public Int64 ImgSize;
public String ImagePrefix;
public String ImagePath;
public String Sex;
public String TZ;
}
and I made a list of RecordInfo like this :
List<RecordInfo> PatientRecords = new List<RecordInfo>();
and I added records to it, but I would like to sort that list based on Patient_ID, sex, Fname, etc.....
Any idea how can I do that?
回答1:
Sure, LINQ makes it easy using OrderBy, OrderByDescending, ThenBy and ThenByDescending:
// Note change from Patient_ID to PatientId for naming conventions.
List<RecordInfo> sorted = records.OrderBy(x => x.PatientId).ToList();
That will create a new list - LINQ is based on queries which project one sequence onto a new one, rather than mutating the existing list.
Alternatively, you could use List<T>.Sort with a custom comparer to sort in-place.
Either way, I'd strongly recommend using properties instead of public fields, and also following .NET naming conventions.
来源:https://stackoverflow.com/questions/12080322/sort-list-of-class-elements