2013-04-09 59 views
3

我想獲得與給定條件匹配的枚舉中所有項目的索引。有沒有比這更清潔的方式?獲取所有匹配項目的索引

var indexes = list.Select((item, index) => new { Item = item, Index = index }).Where(o => Condition(o.Item)).Select(o => o.Index); 
+0

它所泛型類型了IEnumerable的? – Rik 2013-04-09 15:04:31

+1

這可能有幫助 - http://stackoverflow.com/questions/237377/getting-a-collection-of-index-values-using-a-linq-query – 2013-04-09 15:05:11

回答

5

使用標準的LINQ to Object方法 - 不,沒有。您不僅可以提高通過分割查詢可讀性成幾行:

var indexes = list.Select((item, index) => new { Item = item, Index = index }) 
        .Where(o => Condition(o.Item)) 
        .Select(o => o.Index); 

然而,你可以寫爲擴展方法:

public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate) 
{ 
    int index=0; 
    foreach (T element in source) 
    { 
     if (predicate(element)) 
     { 
      yield return index; 
     } 
     index++; 
    } 
} 
+0

鑑於我已經有一個相當廣泛的擴展庫,我喜歡這個解決方案。 – RoadieRich 2013-04-09 15:13:13