2011-12-06 141 views
0

索引值我有一個字符串的集合:"Apple", "Mange", "Pineapple"獲取從集合

我想獲得具有最長的長度字的索引。例如,2對應於最長的單詞"Pineapple"

回答

3

爲了獲得與名稱最長的水果,這樣做:

var fruits = new List<String> { "Apple", "Mange", "Pineapple" }; 
var longestName = (from fruit in fruits 
        orderby fruit.Length descending 
        select fruit).First(); 
var index = fruits.IndexOf(longestName); 

而作爲一個lambda,無特殊原因:

var fruits = new List<String> { "Apple", "Mange", "Pineapple" }; 
var longestName = fruits.OrderByDescending(e => e.Length).First(); 
var index = fruits.IndexOf(longestName); 
+0

Lamda表達式 –

+0

爲什麼它需要是lambda? – Yuck

1

下可以工作了:

var maxItem = fruits 
    .Select((fruit, index) => new { Length = fruit.Length, Index = index }) 
    .Aggregate((max, next) => (next.Length > max.Length) ? next : max); 
var maxIndex = maxItem.Index; 
+0

+1雖然有點棘手閱讀恕我直言,我希望你不介意我的編輯擺脫這些滾動條。 – Yuck

+0

@Yuck同意(我的奇妙滾動條有什麼問題;)) –