C# 带有包含其中列表具有复杂对象的 LINQ Where 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14061935/
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-10 10:34:24  来源:igfitidea点击:

LINQ Where clause with Contains where the list has complex object

c#linq

提问by Sailing Judo

I've seen plenty of examples of LINQ with a contains on a simple list of objects:

我已经看到很多 LINQ 示例,其中包含一个简单的对象列表:

var intList= new List<int>() { 1, 2, 3 };
var result = db.TableRecords.Where(c => intList.Contains(c.RecordId)).ToList();

What I'm trying to do seems slightly more complicated (I think). I have a line of code similar to this one gets me the list I need:

我正在尝试做的事情似乎稍微复杂一些(我认为)。我有一行与此类似的代码,它为我提供了所需的列表:

var xzList = db.Relations.Where(r => someOtherList.Contains(r.zId))
                         .Select(r => new { AId = r.xId, BId = r.zId })
                         .ToList();

And now I want to get the result similar to the previous example but the list now has an anonymous type in it with two ints. So how would I now get resultwhere RecordIdin TableRecordsequals the AIdin the anonymous type for each anonymous type in xzList?

现在我想得到与前一个示例类似的结果,但列表现在有一个带有两个整数的匿名类型。因此,如何将我现在得到result其中RecordIdTableRecords等于AId在匿名类型每个匿名类型xzList

采纳答案by Jon Peterson

Sounds like you are unsure how to get the values out of your anonymous type. You can use GunnerL3510's solution to dump it to a list, or you should be able to inline it like this:

听起来您不确定如何从匿名类型中获取值。您可以使用 GunnerL3510 的解决方案将其转储到列表中,或者您应该能够像这样内联它:

var result = 
    db.TableRecords
        .Where(c => xzList.Select(n => n.AId)
            .Contains(c.RecordId))
        .ToList();

Since you are naming the values in your anonymous type, you refer to them just like properties.

由于您在匿名类型中命名值,因此您可以像引用属性一样引用它们。

If you prefer to do a more structured approach, you can use thismethod.

如果您更喜欢采用更结构化的方法,则可以使用方法。

回答by Jawahar

Something like this:

像这样的东西:

db.TableRecords.Select(c=>c.RecordId).Intercept(xzList.Select(n => n.AId)).Any()