[英]Linq query geting list by comparing Id with an list of objects that have ids
I have the following code:我有以下代码:
var translations = _context.Translations
Where(t => t.LineId == lines.Id)
I got a variable named lines
which is of type List<Line>
every Line
object has Line.Id
我有一个名为
lines
的变量,它的类型是List<Line>
每个Line
对象都有Line.Id
Now I have another table named Translations
I would like to get all Translations which have Line.Id
that is equal to every Line.Id
from the lines
list.现在我有另一个名为
Translations
的表,我想获取Line.Id
等于lines
列表中每个Line.Id
的所有 Translations。
How can I accomplish this in a single LINQ expression?如何在单个 LINQ 表达式中完成此操作?
I need something like this:我需要这样的东西:
var translations = new List<Translation>();
foreach (var line in lines)
{
var translation =
_context.Translations.FirstOrDefault(t => t.LineId == line.Id);
translations.Add(translation);
}
Project an IEnumerable<T>
of your Line.Id
property, then use the result in your query with the Contains
method: Line.Id
属性的IEnumerable<T>
,然后在查询中使用Contains
方法的结果:
var lineIDs = lines.Select(l => l.Id).ToArray();
var translations = _context.Translations
.Where(t => lineIDs.Contains(t.LineId))
.ToList();
Since you want only those translations that have IDs that exist in lines
, this will get you what you want:由于您只需要那些 ID 存在于
lines
中的翻译,这将为您提供您想要的:
var translations = from translation in _context.Translations
join line in lines on translation.LineID equals line.LineID
select translation;
A join
will be faster than invoking a LINQ query for each item in the Translations
"table." join
将比为Translations
“表”中的每个项目调用 LINQ 查询更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.