Sort list of class elements

北慕城南 提交于 2020-01-07 02:16:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!