Check if KeyValuePair exists with LINQ's FirstOrDefault

后端 未结 6 1107
情书的邮戳
情书的邮戳 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.)

提交回复
热议问题