Check if KeyValuePair exists with LINQ's FirstOrDefault

后端 未结 6 1099
情书的邮戳
情书的邮戳 2021-02-03 17:03

I have a dictionary of type

Dictionary

I want to return the first instance where a condition is met using

var         


        
6条回答
  •  囚心锁ツ
    2021-02-03 17:24

    What you want is an Any method that gives you the matching element as well. You can easily write this method yourself.

    public static class IEnumerableExtensions
    {
      public static bool TryGetFirst(this IEnumerable source,
                                              Func predicate,
                                              out TSource first)
      {
        foreach (TSource item in source)
        {
          if (predicate(item))
          {
            first = item;
            return true;
          }
        }
    
        first = default(TSource);
        return false;
      }
    }
    

提交回复
热议问题