Check if KeyValuePair exists with LINQ's FirstOrDefault

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

提交回复
热议问题