查找数组中值的索引。

时间:2022-08-08 21:31:16

Can linq somehow be used to find the index of a value in an array?

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

8 个解决方案

#1


149  

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

That actually gets you the integer index and not the object, regardless of what custom class you have created

这实际上得到了整数索引,而不是对象,不管您创建了什么自定义类。

#2


46  

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

对于数组,您可以使用:Array.FindIndex :

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

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

对于列表,您可以使用List .FindIndex:

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

You can also write a generic extension method that works for any 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;
}

And you can use LINQ as well:

你也可以用LINQ:

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

Please note that this won't short circuit the loop (it will always iterate over the whole collection) and will throw an exception if the condition is not met, rather than returning -1.

请注意,这不会使循环短路(它总是遍历整个集合),如果条件未满足,将抛出异常,而不是返回-1。

#3


9  

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

#4


6  

If you want to find the word you can use

如果你想找到你可以用的词。

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

This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

这将为您提供IsKey为true的第一个项目(如果可能有非您可能想要使用。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();

#5


3  

Try this...

试试这个…

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

#6


2  

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

刚刚发布了IndexWhere()扩展方法(带有单元测试)的实现:

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

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

Example usage:

使用示例:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

#7


0  

int index = -1;
index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;

#8


0  

This solution helped me more, from msdn microsoft:

这个解决方案帮助了我,从微软的msdn。

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

the query is be your toList() query

查询是您的toList()查询。

#1


149  

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

That actually gets you the integer index and not the object, regardless of what custom class you have created

这实际上得到了整数索引,而不是对象,不管您创建了什么自定义类。

#2


46  

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

对于数组,您可以使用:Array.FindIndex :

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

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

对于列表,您可以使用List .FindIndex:

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

You can also write a generic extension method that works for any 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;
}

And you can use LINQ as well:

你也可以用LINQ:

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

Please note that this won't short circuit the loop (it will always iterate over the whole collection) and will throw an exception if the condition is not met, rather than returning -1.

请注意,这不会使循环短路(它总是遍历整个集合),如果条件未满足,将抛出异常,而不是返回-1。

#3


9  

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

#4


6  

If you want to find the word you can use

如果你想找到你可以用的词。

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

This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

这将为您提供IsKey为true的第一个项目(如果可能有非您可能想要使用。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();

#5


3  

Try this...

试试这个…

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

#6


2  

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

刚刚发布了IndexWhere()扩展方法(带有单元测试)的实现:

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

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

Example usage:

使用示例:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

#7


0  

int index = -1;
index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;

#8


0  

This solution helped me more, from msdn microsoft:

这个解决方案帮助了我,从微软的msdn。

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

the query is be your toList() query

查询是您的toList()查询。