1

I need to fetch the records from Table based on ID's in Linq C#. Linq has Contains which works well for String but anyone can help me how i can implement it with Integer Array.

int[] ServiceID = {1, 4, 5}

var result = from table in _context.Table where table.ServiceID.Contains(ServiceID)

I am looking similar filter for Int Array. Please help if anyone have any idea.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
SNR
  • 13
  • 5

2 Answers2

0

int[] ServiceID

Don't call your local variable ServiceID -

  1. local variables should be called in camelCase,
  2. variables representing sets should be plural,
  3. you have a property called ServiceID on your table - calling the local variable the same is a recipe for confusion

The pattern you need to ask is not "does my table.ServiceId contain these wanted serviceIDs", it's "do these wanted serviceIDs contain the table serviceID":


    int[] wantedServiceIDs = {1, 4, 5}

    var result = from table in _context.Table 
                 where wantedServiceIDs.Contains(table.ServiceID)

In SQL terms, this will be translated to

   FROM table
   WHERE serviceId IN (1,4,5)

The confusion, in you're familiar with SQL, is that this is the flip of what you asked for ..

You're supposed to write a LINQ of list.Contains(column) and SQL needs it flipped over to column IN(list) - but of course, when you look at the english language it's logical - x Contains y is the flip of y IN x. Familiarity with SQL's IN, and that the english words "IN" and "Contains" themselves meaning virtually the same thing probably leads a lot of people to try column.Contains(list) when what they need is the inverse

Another possible point of confsuon is that when people think about a column of data in an SQL table, they see multiple values.. But really the database/code only considers one row's worth of data at a time, so it's multiple.Contains(single) or single IN (multiple), and never multipleX.Contains(multipleY)


You can also ask "are any of the wanted service ids equal to the table service id"

var result = from table in _context.Table where 
  wantedServiceIDs.Any(wantedId => table.ServiceID == wantedId)

This latter form is trickier, because it often leads you to believe you can use complex expressions to refine your table, and you can't so I'd strive to avoid using it.. For example

var wantedServices = new[] { new Service{ ID = 1, name = ""}, new Service{ ID = 2, name = ""} };

//this wouldn't work/not be translatable to SQL
var result = from table in _context.Table where 
  wantedServices.Any(wantedService => table.ServiceID == wantedService.ID)

Using the simple "list of ID ints" .Contains discourages you from trying this form

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

You could write something like this (using Contains). also change you array variable name to ServiceIDs

int[] ServiceIDs = {1, 4, 5}  
var result = ServiceID.Where(i => ServiceIDs.Contains(i.OrderId));
Ran Turner
  • 14,906
  • 5
  • 47
  • 53