在C#中对列表进行排序

3

我有一个类,长这样:

class Record
{
    public string host { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public string RunAsUser { get; set; }
    public string Status { get; set; }
    public string StartMode { get; set; }
}

这是一个类的列表:

List<Record> Records = new List<Record>();

这个列表包含许多条目。如何按照 Record.host 的字母顺序对此列表进行排序?

是否有内置函数可以使用,还是我需要编写自己的排序函数?如果需要自己编写,是否可以给我一些伪代码指导方向?

2个回答

8

如果你只需要按排序顺序迭代它们,你可以使用Linq进行排序。

Records.OrderBy(r => r.host)

否则,您可以调用:
Records.sort((x, y) => string.Compare(x.host, y.host)); 

永久地对列表进行排序。

只要您想要升序排列。另外:List<Record> acending = descending.OrderBy(x => x.host).ThenBy(x => x.name).ToList(); - JohnB

2
以下内容将对列表本身进行排序:
Records.Sort((a, b) => String.Compare(a.host, b.host));

3
注意:更安全的做法是使用string.Compare(a.host,b.host) - 这样如果 a.host 为空,您就不必担心它。 - Marc Gravell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接