【问题标题】:Partial key match in a sorted List<string>排序列表中的部分键匹配<string>
【发布时间】:2011-07-06 14:00:14
【问题描述】:

假设我有一个像{"a1", "a2", "b0", "b2", "c1", ...} 这样的字符串排序列表,并且想要确定从“b”开始的第一个元素的索引。在 .NET 4 中获取它的最快方法是什么?内存不是问题。

【问题讨论】:

  • 你的意思是你想要第一个以“b”作为第一个字符的元素的索引吗? (即 2)
  • this的可能重复
  • 谢谢,乔尔!正是我需要的!

标签: .net algorithm optimization search


【解决方案1】:

使用这个:

var list = new List<string> { "a1", "a2", "b0", "b2", "c1" };
int index = list.FindIndex(x => x.StartsWith("b"));

如果您的列表很大并且性能是一个问题,那么请考虑 Joel Rondeau 在对您的问题的评论中指出的可能重复的答案。

【讨论】:

  • 这太棒了!我用List&lt;T&gt;三年了,不知道这个方法。
【解决方案2】:

如果“最快”是指“最容易实现”,那么

大概是这样的:

static int FirstIndex(this IEnumerable<T> coll, Predicate<T> pred)
{
    var it = coll.GetEnumerator();

    int index = 0;

    while(it.MoveNext())
    {
        if(pred(it.Current))
        {
           return index;
        }
        index++;
    }

     throw new ObjectNotFoundException();
}    

{"a1", "a2", "b0", "b2", "c1"}.FirstIndex(s => s.StartsWith("b"));

或者使用 F# 中的 Seq module(请注意,我从未尝试使用 C# 中的这些...这种语法可能是错误的。):

Seq.findIndex(s => s.StartsWith("b"))(strings);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 2011-07-06
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多