开发者

Find index of a value in an array

开发者 https://www.devze.com 2022-12-12 03:37 出处:网络
Can linq somehow be used to fin开发者_运维问答d the index of a value in an array? For instance, this loop locates the key index within an array.

Can linq somehow be used to fin开发者_运维问答d the index of a value in an array?

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


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


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

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:

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


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


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

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


Try this...

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


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

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

Example usage:

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


This solution helped me more, from msdn microsoft:

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

query is your toList() query.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号