Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I accomplish this in a single LINQ expression?

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);
 }

>Solution :

Project an IEnumerable<T> of your Line.Id property, then use the result in your query with the Contains method:

var lineIDs = lines.Select(l => l.Id).ToArray();

var translations = _context.Translations
    .Where(t => lineIDs.Contains(t.LineId))
    .ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading