c# - 我可以将嵌入式 lambda 与 Contains 方法一起使用吗?

标签 c# linq lambda contains

我想用 FindAll 过滤一个列表

如果我写:

.FindAll(
    p => p.Field == Value && 
    p.otherObjList.Contains(otherObj));

没关系,但如果我写

.FindAll(
    p => p.Field == Value && 
    p.otherObjList.Contains(
        q => q.Field1 == Value1 && 
        q.Field2 == Value2));

我收到 C# 语法错误消息:Unknown Method FindAll(?) of .. the otherObjList

我无法准确定义 otherObj,因为我只知道两个字段 Field1 和 Field2 的值。

我做错了什么?在这种情况下我能做什么?

最佳答案

大多数集合类型和 LINQ 版本的 Contains() 方法需要一个与集合类型相同的参数,而不是 lambda。

看来您只是想检查是否有任何项目符合某些条件。你应该使用 Any()方法。

.FindAll(p => p.Field == Value
           && p.otherObjList.Any(q => q.Field1 == Value1 && q.Field2 == Value2))

关于c# - 我可以将嵌入式 lambda 与 Contains 方法一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103323/

相关文章:

c# - 类型 'System.Int16' 的表达式不能用于返回类型 'System.Object'

c# - 将 Excel 中的行转换为自定义实体

c# - 构建代理需求的问题未针对 android 构建进行验证

c# - 每个团队成员和分支的不同 *.csproj/*.config 设置

c# - 3 个数组到 1 个 IEnumerable<test>

.net - LINQ GroupBy 对象还是仅匿名类型?

c# - Math.Sqrt(2/3) 返回 0

c# - 使用ListView控件显示数据但加入一个引用表

python - 如何计算 pandas groupby 中的所有正值和负值?

c++ - 是否可以这样编码 :while(lambda){}