I have an MVC3 C#.Net web app. I have the below string array.
public static string[] HeaderNamesWbs = new[] { WBS_NUMBER, BOE_TITLE, SOW_DESCRIPTION, HARRIS_WIN_THEME, COST_BOGEY };
I want to find the Index of a given entry when in another loop. I thought the list would have an IndexOf. I can't find it. Any ideas?
LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.
To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.
In C#, IndexOf() method is a string method. This method is used to find the zero-based index of the first occurrence of a specified character or string within the current instance of the string. The method returns -1 if the character or string is not found.
The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With