c#用两个不同的东西排序列表
本文关键字:列表 排序 两个 | 更新日期: 2023-09-27 18:01:20
假设我有以下列表:
var someList = new List<SomeObject>();
包含以下条目:
SomeObject。字段
Apple
Orange
FruitBowl_Outside
Banana
Grape
FruitBowl_Inside
我想对这个列表进行排序,以便FruitBowl
条目位于底部,并且在此基础上,所有内容都是按字母顺序排列的。
序字:
SomeObject。字段
Apple
Banana
Grape
Orange
FruitBowl_Inside
FruitBowl_Outside
可以使用OrderBy()和ThenBy()方法:
var orderedList = someList.OrderBy(obj => obj.Field.StartsWith("FruitBowl_"))
.ThenBy(obj => obj.Field);
您可以创建自己的IComparer并将其传递给List。排序方法。我将很快发布代码。
List<Record> list = new List<Record>();
list.Add(new Record("Apple"));
list.Add(new Record("Orange"));
list.Add(new Record("FruitBowl_Outside"));
list.Add(new Record("Banana"));
list.Add(new Record("Grape"));
list.Add(new Record("FruitBowl_Inside"));
list.Sort(new RecordComparer());
public class Record {
public Record(string data) {
this.data = data;
}
private string data;
public string Data {
get { return data; }
set {
data = value;
}
}
}
public class RecordComparer : IComparer<Record> {
public int Compare(Record x, Record y) {
if(x.Data.Contains("FruitBowl") && !y.Data.Contains("FruitBowl"))
return 1;
if(y.Data.Contains("FruitBowl") && !x.Data.Contains("FruitBowl"))
return -1;
return x.Data.CompareTo(y.Data);
}
}
如何:
someList.OrderBy(a => a.Field.StartsWith("FruitBowl")).ThenBy(a => a.Field);
您可以使用List.Sort()与自定义比较方法-参见这里。
这个怎么样↓
someList.Sort(new Comparison<string>((x, y) => { return x.StartsWith("FruitBowl") ^ y.StartsWith("FruitBowl") ? (x.StartsWith("FruitBowl") ? 1 : -1) : x.CompareTo(y); }));
与样本↓
static void Main(string[] args)
{
List<string> lstData = new List<string>()
{
"Apple",
"Orange",
"FruitBowl_Outside",
"Banana",
"Grape",
"FruitBowl_Inside"
};
lstData.Sort(new Comparison<string>((x, y) => { return x.StartsWith("FruitBowl") ^ y.StartsWith("FruitBowl") ? (x.StartsWith("FruitBowl") ? 1 : -1) : x.CompareTo(y); }));
foreach (string data in lstData)
Console.WriteLine(data);
Console.ReadLine();
}