c# - IEnumerable<type> 不包含 'Contains' 的定义

标签 c# .net linq

我有 2 个类和 2 个这些类的 IEnumerable 列表:

public class Values
{
    public int Value { get; set; }
    public DateTime SomeDate { get; set; }
}

public class Holidays
{
    public DateTime holiday { get; set; }
}

IEnumerable<Values> values;
IEnumerable<Holidays> holidays;

接下来,我尝试选择“someDate”不在“假期”中的那些“值”

var query = values.Where(x=> !holidays.Contains(x.someDate));

但是,这给了我 IEnumerable<Holidays> does not contain a definition of 'Contains' 的错误.

System.Linq 已添加到 using

我相信这与集合有关,但我不知道是什么。

最佳答案

当您使用 Contains 时,您要查找的对象必须匹配类型 TIEnumerable<T> .因此,您无法搜索 IEnumerable<A>对于 B 类型的包含对象因为没有隐含的方法来比较两者。

如其他答案中所述,使用 Any 并自己传入比较。

或者,这也是您可以使用 Select 的情况。其次是 Contains ,尽管在某些情况下这可能不太可读:

var query = values
    .Where(x => !holidays
        .Select(h => h.holiday)
        .Contains(x.someDate));

关于c# - IEnumerable<type> 不包含 'Contains' 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36159497/

相关文章:

c# - 基于字典排序 IEnumerable<T> 对象

c# - 如何为所有 IEnumerable<Int32> 覆盖 ToString() 方法?

.net - SSL 证书验证 - 是否涉及缓存?

c# - 如何在 GET 请求中包含内容?

LINQ:字段不是引用字段

c# - 有没有办法使用部分填充的对象搜索 List<T>?

asp.net-mvc - 存储库模式 : One repository class for each entity?

c# - 是否可以在不复制的情况下为多个组件创建一个 Blazor 范围的 CSS 文件?

c# - 将通用 Windows C# 类库引用添加到通用 Windows C++ DLL 项目 Visual Studio 2015

c# - 无法将类型为 'System.DBNull' 的对象转换为类型 'System.String`