C# 使用 LINQ 的 FirstOrDefault 检查 KeyValuePair 是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/793897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:25:29  来源:igfitidea点击:

Check if KeyValuePair exists with LINQ's FirstOrDefault

c#linqnull

提问by Steve

I have a dictionary of type

我有一个类型的字典

Dictionary<Guid,int>

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

我想返回满足条件的第一个实例

var available = m_AvailableDict.FirstOrDefault(p => p.Value == 0)

However, how do I check if I'm actually getting back a KeyValuePair? I can't seem to use != or == to check against default(KeyValuePair) without a compiler error. There is a similar thread herethat doesn't quite seem to have a solution. I'm actually able to solve my particular problem by getting the key and checking the default of Guid, but I'm curious if there's a good way of doing this with the keyvaluepair. Thanks

但是,如何检查我是否真的取回了 KeyValuePair?如果没有编译器错误,我似乎无使用 != 或 == 来检查 default(KeyValuePair) 。有一个类似的线程在这里并不十分似乎有一个解决方案。我实际上能够通过获取密钥并检查 Guid 的默认值来解决我的特定问题,但是我很好奇是否有使用键值对执行此操作的好方。谢谢

采纳答案by Marc Gravell

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

如果你只关心存在,你可以用ContainsValue(0)orAny(p => p.Value == 0)代替?按搜索对于 a 是不寻常的Dictionary<,>;如果您按关键字搜索,则可以使用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 nullif not found.

这将返回一个-null如果找不到,也会返回一个

回答by pomarc

you could check if

你可以检查一下

available.Key==Guid.Empty

回答by Jon Skeet

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 firstentered 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 solutionis the most appropriate.)

(这是假设您确实想知道密钥 - 如果您只是在进行存在检查之后,那么Marc 的解决方案是最合适的。)

回答by Samuel

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

您想要的是一种Any同时为您提供匹配元素的方。您可以轻松地自己编写此方。

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;
  }
}

回答by Florian Sandro V?lkl

Use the default() keyword.

使用 default() 关键字。

bool exists = !available.Equals(default(KeyValuePair<Guid, int>));

回答by kevinpo

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:

在不指定类型的情况下检查结构(例如 KeyValuePair)的默认值的一种方是使用 Activator 创建一个新实例:

if (available.Equals(Activator.CreateInstance(available.GetType())))
{
    Console.WriteLine("Not Found!");
}