LINQ indexOf a particular entry

MikeTWebb picture MikeTWebb · Feb 15, 2012 · Viewed 27.3k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · Feb 15, 2012

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