C# List 的自定义 Sort 方法应用
ITPOW2018/12/13 9:39:52
如何自定义一个 ICompare 的类来进行比较,然后排序呢?
首先实例化 ICompare
private class ComparerSiteForList : IComparer<Site> { public int Compare(Site x, Site y) { if (x.Id > y.Id) { return 1; } else if (x.Id == y.Id) { return 0; } else { return -1; } } }
应用就简单了
List<Site> sites = GetSites(); sites.Sort(new ComparerSiteForList());
也可以用省略的写法
sites.Sort((x, y) => { if (x.Id > y.Id) { return 1; } else if (x.Id == y.Id) { return 0; } else { return -1; } });
<<返回首页<<