Home > OS >  Linq query geting list by comparing Id with an list of objects that have ids
Linq query geting list by comparing Id with an list of objects that have ids

Time:07-01

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.

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

CodePudding user response:

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

CodePudding user response:

Since you want only those translations that have IDs that exist in lines, this will get you what you want:

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."

  • Related