【问题标题】:Searching List<string> based on string match根据字符串匹配搜索 List<string>
【发布时间】:2019-04-12 13:52:10
【问题描述】:

我有以下c#List&lt;string&gt;

var lists = new List<string>
{
    "a", "b", "c", "ee", "ja"
}

我现在想查找字母数字值小于或等于 d 的最后一项的索引,在本例中为 2 - 表示“c”

谁能建议我如何做到这一点?它需要快速,因为它将搜索大型列表。

是否还有一种方法可以对最接近 "ef" 的匹配项或任何一组多个字符进行相同的比较

编辑 - 我知道我可以编写一个 for 循环来执行此操作,但还有其他方法可以执行此操作吗?也许是一个内置函数。

我知道它是否是一个我可以使用 Linq 的数值函数。

【问题讨论】:

  • 第一项真的第一吗?那么为什么不“a”它也小于“d”。也许你想得到最后一项?

标签: c# list search


【解决方案1】:

你想要FindLastIndex

var index = lists.FindLastIndex(value => value.CompareTo("d") < 0);

注意:您必须使用CompareTo,因为&lt; 不存在字符串。

【讨论】:

    【解决方案2】:

    在您的List 已排序的条件下,使用BinarySearch 方法将获得出色的性能。如果不是,请不要使用此方法,因为您会得到不正确的结果。

    // List.BinarySearch returns:
    // The zero-based index of item in the sorted System.Collections.Generic.List`1,
    // if item is found; otherwise, a negative number that is the bitwise complement
    // of the index of the next element that is larger than item or, if there is no
    // larger element, the bitwise complement of System.Collections.Generic.List`1.Count.
    int pos = lists.BinarySearch("d");
    int resultPos = pos >= 0 ? pos : ~pos - 1;
    Console.WriteLine("Result: " + resultPos);
    

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 2012-03-12
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多