简体   繁体   English

Linq 通过将 Id 与具有 id 的对象列表进行比较来获取列表

[英]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.

相关问题 LINQ查询将ID与SingleOrDefault查询中的列表中的ID进行比较 - LINQ Query comparing Id with an Id in a list inside SingleOrDefault query 删除所有ID不等于ID列表的对象的LINQ查询现在可以正常工作 - LINQ query for removing all objects with an id not equal to a list of ids now workign properly SQLite 和 LINQ:查找所有具有子列表的对象,其中所有 id 都存在于提供的 ID 列表中 - SQLite and LINQ: find all objects that have a sub list with all ids present in a supplied list of IDs linq 返回带有 id 列表的查询 - linq returning query with a list of ids 当您有对象ID列表时,有效的linq查询返回对象 - Efficient linq query to return objects when you have a list of object id's C#使用LINQ将ID列表与对象列表中的每个ID进行比较 - C# compare a list of IDs to each ID in a list of objects using LINQ 我可以使用LINQ检查列表中的对象是否具有唯一ID吗? - Can I use LINQ to check if objects in a list have a unique ID? LINQ查询其中ID不作为对象列表中的属性存在 - LINQ query Where ID does not exist as a property in a list of objects LINQ 查询对象列表,里面有多个对象列表 - LINQ query list of objects with multiple list of objects in it 如何编写 Linq 查询以检查列表是否具有该 ID - How to write Linq query to check whether List have that id
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM