查找数组中值的索引

ini*_*ero 107 c# linq arrays

linq可以用某种方式来查找数组中值的索引吗?

例如,此循环在数组中定位键索引.

for (int i = 0; i < words.Length; i++)
{
    if (words[i].IsKey)
    {
        keyIndex = i;
    }
}
Run Code Online (Sandbox Code Playgroud)

sid*_*ews 174

int keyIndex = Array.FindIndex(words, w => w.IsKey);
Run Code Online (Sandbox Code Playgroud)

无论您创建了哪个自定义类,这实际上都会获得整数索引而不是对象


Pao*_*tti 57

对于阵列,您可以使用 Array.FindIndex<T>::

int keyIndex = Array.FindIndex(words, w => w.IsKey);
Run Code Online (Sandbox Code Playgroud)

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

int keyIndex = words.FindIndex(w => w.IsKey);
Run Code Online (Sandbox Code Playgroud)

您还可以编写适用于以下任何内容的通用扩展方法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;
}
Run Code Online (Sandbox Code Playgroud)

你也可以使用LINQ:

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

  • 还有[List(T).FindIndex](http://msdn.microsoft.com/en-us/library/0k601hd9.aspx)方法 (2认同)

Lum*_*mpN 10

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();
Run Code Online (Sandbox Code Playgroud)

  • +1但是,如果项目不存在怎么办?我们将得到0,但索引是-1 (2认同)

Gri*_*zly 6

如果你想找到你可以使用的单词

var word = words.Where(item => item.IsKey).First();
Run Code Online (Sandbox Code Playgroud)

这为您提供了IsKey为真的第一个项目(如果您可能想要使用非项目 .FirstOrDefault()

要获得可以使用的项目和索引

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
Run Code Online (Sandbox Code Playgroud)

  • @initialZero检查`First`的重载,它需要一个谓词,你不需要`Where`. (5认同)