2011-03-01 31 views
1

假設我有一個排序的字符串列表,如{"a1", "a2", "b0", "b2", "c1", ...},並且想要確定從「b」開始的第一個元素的索引。 .NET 4中最快的方式是什麼?內存不是問題。排序列表中的部分鍵匹配<string>

+0

你的意思是你想要第一個具有「b」的元素的索引作爲第一個字符嗎? (即2) – Toby 2011-03-01 15:01:46

+2

[this]的可能的重複(http://stackoverflow.com/questions/457160/the-most-efficient-algorithm-to-find-first-prefix-match-from-a-sorted-string- arrael) – 2011-03-01 15:05:49

+0

謝謝,喬爾!正是我需要的! – UserControl 2011-03-01 16:16:07

回答

0

如果「最快」你的意思是「最容易實現的」,那麼

事情大致是這樣的:

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

或者使用Seq module從F#(需要注意的,我從來沒有使用這些從試C#...這句法也許是錯誤的)。

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

使用此:

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

如果您的清單非常龐大,而且表現是一個問題,那麼請考慮Joel Rondeau在他對您的問題的評論中提到的可能重複的答案。

+0

這太棒了!我使用了'List '三年,並且不知道這種方法。 – 2011-03-01 15:22:24