C# 查找数组中某个值的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1764970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:37:38  来源:igfitidea点击:

Find index of a value in an array

c#arrayslinq

提问by initialZero

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

采纳答案by sidney.andrews

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

无论您创建了什么自定义类,这实际上都会为您提供整数索引而不是对象

回答by initialZero

Try this...

尝试这个...

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

回答by Grizzly

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 为真的第一个项目(如果可能有非您可能想要使用 .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();

回答by joelsand

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

回答by Marcel Valdez Orozco

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

回答by LumpN

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

回答by Paolo Moretti

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

对于数组,您可以使用 Array.FindIndex<T>

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


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

对于列表,您可以使用List<T>.FindIndex

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


You can also write a generic extension method that works for any Enumerable<T>:

您还可以编写适用于任何的通用扩展方法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})
    .FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;

回答by Roshna Omer

This solution helped me more, from msdn microsoft:

这个解决方案帮助了我更多,来自msdn microsoft

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

queryis your toList()query.

query是您的toList()查询。