【发布时间】:2020-07-22 18:00:58
【问题描述】:
我有一个如下机构列表:
List<Institute> instituteList = new List<Institute>(){
new Institute{Id=1, Name= "[12345] saleha ideal school"},
new Institute{Id=2, Name= "[456987] ideal school & college"},
new Institute{Id=3, Name= "[698745] dhaka faizul islam ideal school"},
new Institute{Id=4, Name= "[596314] nurul haque ideal school"}
}
我正在尝试通过搜索文本的相关性来排序此列表:ideal,因为名称包含 ideal 的机构将排在第一位。
因此,排序后的列表将如下:
List<Institute> instituteList = new List<Institute>(){
new Institute{Id=2, Name= "[456987] ideal school & college"},
new Institute{Id=1, Name= "[12345] saleha ideal school"},
new Institute{Id=4, Name= "[596314] nurul haque ideal school"}
new Institute{Id=3, Name= "[698745] dhaka faizul islam ideal school"},
}
以下两种方法我都试过了:
instituteList = instituteList.OrderByDescending(x => x.Name.Contains("ideal")).ToList();
instituteList = instituteList.OrderBy(i => "ideal".IndexOf(i.Name)).ToList();
但是没有人在工作。
【问题讨论】:
-
您的
instituteList初始化程序将无法编译。另外,使用Sort方法看起来更自然,而不是在排序后重新分配列表 -
使用排序方法有效!。 @PavelAnikhouski