LINQ indexOf a particular entry
Well you can use Array.IndexOf
:
int index = Array.IndexOf(HeaderNamesWbs, someValue);
Or just declare HeaderNamesWbs
as an IList<string>
instead - which can still be an array if you want:
public static IList<string> HeaderNamesWbs = new[] { ... };
Note that I'd discourage you from exposing an array as public static
, even public static readonly
. You should consider ReadOnlyCollection
:
public static readonly ReadOnlyCollection<string> HeaderNamesWbs =
new List<string> { ... }.AsReadOnly();
If you ever want this for IEnumerable<T>
, you could use:
var indexOf = collection.Select((value, index) => new { value, index })
.Where(pair => pair.value == targetValue)
.Select(pair => pair.index + 1)
.FirstOrDefault() - 1;
(The +1 and -1 are so that it will return -1 for "missing" rather than 0.)
I'm late to the thread here. But I wanted to share my solution to this. Jon's is awesome, but I prefer simple lambdas for everything.
You can extend LINQ itself to get what you want. It's fairly simple to do. This will allow you to use syntax like:
// Gets the index of the customer with the Id of 16.
var index = Customers.IndexOf(cust => cust.Id == 16);
This is likely not part of LINQ by default because it requires enumeration. It's not just another deferred selector/predicate.
Also, please note that this returns the first index only. If you want indexes (plural), you should return an IEnumerable<int>
and yield return index
inside the method. And of course don't return -1. That would be useful where you are not filtering by a primary key.
public static int IndexOf<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
var index = 0;
foreach (var item in source) {
if (predicate.Invoke(item)) {
return index;
}
index++;
}
return -1;
}
If you want to search List with a function rather than specifying an item value, you can use List.FindIndex(Predicate match).
See https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findindex?view=netframework-4.8
Right List
has IndexOf(), just declare it as ILIst<string>
rather than string[]
public static IList<string> HeaderNamesWbs = new List<string>
{
WBS_NUMBER,
BOE_TITLE,
SOW_DESCRIPTION,
HARRIS_WIN_THEME,
COST_BOGEY
};
int index = HeaderNamesWbs.IndexOf(WBS_NUMBER);
MSDN: List(Of T).IndexOf Method (T)