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
LINQ Where clause with Contains where the list has complex object
提问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 result
where RecordId
in TableRecords
equals the AId
in the anonymous type for each anonymous type in xzList
?
现在我想得到与前一个示例类似的结果,但列表现在有一个带有两个整数的匿名类型。因此,如何将我现在得到result
其中RecordId
在TableRecords
等于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()