如何使用LINQ获取索引?

给定这样的数据源:

var c = new Car[]

{

new Car{ Color="Blue", Price=28000},

new Car{ Color="Red", Price=54000},

new Car{ Color="Pink", Price=9999},

// ..

};

如何使用LINQ 找到满足特定条件的第一辆汽车的 ?

编辑:

我可以想到这样的东西,但是看起来很可怕:

int firstItem = someItems.Select((item, index) => new    

{

ItemName = item.Color,

Position = index

}).Where(i => i.ItemName == "purple")

.First()

.Position;

用一个简单的旧循环解决这个问题是最好的吗?

回答:

An IEnumerable不是有序集。

尽管大多数IEnumerables是有序的,但有些(例如DictionaryHashSet)却没有订购。

因此,LINQ没有IndexOf方法。

但是,您可以自己写一个:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>

///<param name="items">The enumerable to search.</param>

///<param name="predicate">The expression to test the items against.</param>

///<returns>The index of the first matching item, or -1 if no items match.</returns>

public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {

if (items == null) throw new ArgumentNullException("items");

if (predicate == null) throw new ArgumentNullException("predicate");

int retVal = 0;

foreach (var item in items) {

if (predicate(item)) return retVal;

retVal++;

}

return -1;

}

///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>

///<param name="items">The enumerable to search.</param>

///<param name="item">The item to find.</param>

///<returns>The index of the first matching item, or -1 if the item was not found.</returns>

public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }

以上是 如何使用LINQ获取索引? 的全部内容, 来源链接: utcz.com/qa/403758.html

回到顶部