Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ To Query Int Ids From An Array

Tags:

c#

linq

I have an array of Ids that I want to pass to the entity framework via a Linq query to return any matches

I have written Linq queries that can convert Ids to strings and use the 'Contains' operator, such as:

Model

public class Order {
  public long OrderId { get; set; }
  public string Name { get; set; } ...}

Order[] orders = { new Order { OrderId = 123, Name = "Order1" }, new Order {...},...};

for which I can use something like:

long[] testArray = {123, 456};

and then

var result = orders.Where(i => testArray.ToString().Contains(i.OrderId.ToString()));

but do I really need to keep casting the Ids to strings? It looks as though I can't access the 'Contains' if I keep them as ints.

Ultimately, I want to be able to use this as part of a query that accesses the Entity Framework and so passes the query as part of an IQueryable<> to make sure I am not returning reams of data when I only want a handfull, such as:

var orders = _repo.Orders().Where(i => orderArray.Contains(i.OrderId));

So any solution it would be useful if the query params (the int array) through the EF rather than getting all of the data and then checking it in memory.

Cheers!

like image 465
GrahamJRoy Avatar asked Jun 14 '12 09:06

GrahamJRoy


People also ask

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

What kind of data can be queried with LINQ?

LINQ offers common syntax for querying any type of data source; for example, you can query an XML document in the same way as you query a SQL database, an ADO.NET dataset, an in-memory collection, or any other remote or local data source that you have chosen to connect to and access by using LINQ.

What are the different LINQ query methods?

There are the following two ways to write LINQ queries using the Standard Query operators, in other words Select, From, Where, Orderby, Join, Groupby and many more. Using lambda expressions. Using SQL like query expressions.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

but do I really need to keep casting the Ids to strings

Absolutely not. It's not clear what bars is, but assuming it should really be orders, you could use:

var result = orders.Where(i => testArray.Contains(i.OrderId));

or perform a join:

var result = orders.Join(testArray, o => o.OrderId, id => id, (o, id) => o);
like image 106
Jon Skeet Avatar answered Sep 28 '22 19:09

Jon Skeet