Check if KeyValuePair exists with LINQ's FirstOrDefault

后端 未结 6 1109
情书的邮戳
情书的邮戳 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:08

    I suggest you change it in this way:

    var query = m_AvailableDict.Where(p => p.Value == 0).Take(1).ToList();
    

    You can then see whether the list is empty or not, and take the first value if it's not, e.g.

    if (query.Count == 0)
    {
        // Take action accordingly
    }
    else
    {
        Guid key = query[0].Key;
        // Use the key
    }
    

    Note that there's no real concept of a "first" entry in a dictionary - the order in which it's iterated is not well-defined. If you want to get the key/value pair which was first entered with that value, you'll need an order-preserving dictionary of some kind.

    (This is assuming you actually want to know the key - if you're just after an existence check, Marc's solution is the most appropriate.)

    0 讨论(0)
  • 2021-02-03 17:11

    A way to check against the default value of a struct such as KeyValuePair without specifying the type is to create a new instance using Activator:

    if (available.Equals(Activator.CreateInstance(available.GetType())))
    {
        Console.WriteLine("Not Found!");
    }
    
    0 讨论(0)
  • 2021-02-03 17:18

    Use the default() keyword.

    bool exists = !available.Equals(default(KeyValuePair<Guid, int>));
    
    0 讨论(0)
  • 2021-02-03 17:18

    you could check if

    available.Key==Guid.Empty
    
    0 讨论(0)
  • 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<TSource>(this IEnumerable<TSource> source,
                                              Func<TSource, bool> predicate,
                                              out TSource first)
      {
        foreach (TSource item in source)
        {
          if (predicate(item))
          {
            first = item;
            return true;
          }
        }
    
        first = default(TSource);
        return false;
      }
    }
    
    0 讨论(0)
  • 2021-02-03 17:29

    If you just care about existence, you could use ContainsValue(0) or Any(p => p.Value == 0) instead? Searching by value is unusual for a Dictionary<,>; if you were searching by key, you could use TryGetValue.

    One other approach:

    var record = data.Where(p => p.Value == 1)
         .Select(p => new { Key = p.Key, Value = p.Value })
         .FirstOrDefault();
    

    This returns a class - so will be null if not found.

    0 讨论(0)
提交回复
热议问题