开发者

Partial key match in a sorted List<string>

Say I have a sorted list of strings like {"a1", "a2", "b0", "b2", "c1", ...}开发者_如何学C and want to determine an index of the first element starting from "b". What is the fastest way to get it in .NET 4? Memory is not a problem.


Use this:

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

If your list is huge and performance is an issue, than consider the answer in the possible duplicate as noted by Joel Rondeau in his comment to your question.


If for "fastest" you mean "easiest to implement" then

Something roughly like this:

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"));

Or using the Seq module from F# (caveat, I've never tried using these from C#... this syntax is probably wrong.):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜