查找数组中值的索引

Linq 可以用来查找数组中值的索引吗?

For instance, this loop locates the key index within an array.

for (int i = 0; i < words.Length; i++)
{
if (words[i].IsKey)
{
keyIndex = i;
}
}
161299 次浏览

试试这个..。

var key = words.Where(x => x.IsKey == true);

如果你想找到你能用的词

var word = words.Where(item => item.IsKey).First();

这将为您提供第一个 IsKey 为 true 的项(如果可能有 non,则可能需要使用 .FirstOrDefault())

To get both the item and the index you can use

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
int keyIndex = Array.FindIndex(words, w => w.IsKey);

无论您创建的是什么自定义类,它实际上都将获得整数索引,而不是对象

Just posted my implementation of IndexWhere() extension method (with unit tests):

Http://snipplr.com/view/53625/linq-index-of-item——indexwhere/

示例用法:

int index = myList.IndexWhere(item => item.Something == someOtherThing);
int index = -1;
index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;
int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

For arrays you can use: Array.FindIndex<T> :

int keyIndex = Array.FindIndex(words, w => w.IsKey);

For lists you can use List<T>.FindIndex:

int keyIndex = words.FindIndex(w => w.IsKey);

您还可以编写一个适用于任何 Enumerable<T>的通用扩展方法:

///<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;
}

你也可以使用 LINQ:

int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;

这个解决方案对我的帮助更大,来自 微软:

var result =  query.AsEnumerable().Select((x, index) =>
new { index,x.Id,x.FirstName});

querytoList()查询。