【问题标题】:Order list by serach text relevance in C#在 C# 中按搜索文本相关性排序列表
【发布时间】: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

标签: c# .net string


【解决方案1】:

你几乎在那里,但不完全是。试试这个:

instituteList.Sort((a, b) => a.Name.ToLower().IndexOf(query.ToLower()).CompareTo(b.Name.ToLower().IndexOf(query.ToLower())));

注意:手机写的,可能有错别字...

【讨论】:

  • instituteList.Sort((a, b) => a.Name.ToLower().IndexOf(query.ToLower()).CompareTo(b.Name.ToLower().IndexOf(query.降低())));工作。 @Zohar Peled
  • 当然,我太傻了,忘记了 Name 属性...明天会编辑它
  • 很高兴为您提供帮助 ;-)
猜你喜欢
  • 2012-11-09
  • 2011-01-26
  • 2011-08-26
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多