0

I have a list of integers: ids. There is also collection, IdNames which comes from an sql table. For each integer in ids I want to find the matching id in, IdNames. Then for each record in IdNames that has a matching id I'd like to select the value in the Name and DisplayName columns and the id.

So here is the table IdNames

Id   |     Name    |  DisplayName
--------------------------------
1    |   fistName  | firstDisplayName
2    |  secondName | secondDisplayName
3    |  thirdName  | thirdDisplayName

If ids contained the integers 2 and 3, I'd want this collection to be returned

 Id   |     Name    |  DisplayName
--------------------------------  
 2    |  secondName | secondDisplayName
 3    |  thirdName  | thirdDisplayName

How would I write this as a linq query?

I stared writing it like this: IdNames.Select(x => x.Id == ids.Any()), but obviously it's not right.

navig8tr
  • 1,400
  • 7
  • 26
  • 56

2 Answers2

1
var idNames = from idName in DataContext.IdNames
              where ids.Contains(idName.Id)
              select idName;

Good enough?

Stilgar
  • 21,249
  • 9
  • 61
  • 99
1

Use Join in Linq-To-Objects("I have a list of integers: ids. There is also collection, IdNames"):

var query = from id in ids
            join idName in IdNames
            on id equals idName.Id
            select idName;

Why is LINQ JOIN so much faster than linking with WHERE?

Community
  • 1
  • 1
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891