Reputation: 6367
Can linq somehow be used to find 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;
}
}
Upvotes: 127
Views: 176692
Reputation: 55946
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;
Upvotes: 73
Reputation: 721
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.
Upvotes: 1
Reputation: 5256
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
Upvotes: 207
Reputation: 3015
int index = -1;
index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;
Upvotes: 0
Reputation: 2275
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);
Upvotes: 2
Reputation: 20191
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();
Upvotes: 7