LINQ indexOf a particular entry

后端 未结 4 1086
不思量自难忘°
不思量自难忘° 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:11

    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 and yeild 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(this IEnumerable source, Func predicate) {
    
         var index = 0;
         foreach (var item in source) {
            if (predicate.Invoke(item)) {
               return index;
            }
            index++;
         }
    
         return -1;
      }
    

提交回复
热议问题