LINQ indexOf a particular entry

后端 未结 4 1087
不思量自难忘°
不思量自难忘° 2021-01-01 11:28

I have an MVC3 C#.Net web app. I have the below string array.

    public static string[] HeaderNamesWbs = new[]
                                       {
            


        
4条回答
  •  醉酒成梦
    2021-01-01 12:12

    Well you can use Array.IndexOf:

    int index = Array.IndexOf(HeaderNamesWbs, someValue);
    

    Or just declare HeaderNamesWbs as an IList instead - which can still be an array if you want:

    public static IList 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 HeaderNamesWbs =
        new List { ... }.AsReadOnly();
    

    If you ever want this for IEnumerable, 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.)

提交回复
热议问题