Using LINQ To Query Int Ids from an Array

I have an Ids array that I want to pass to the entity infrastructure through a Linq query to return any matches

I wrote Linq queries that can convert identifiers to strings and use the "Contains" operator, for example:

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 continue pouring identifiers into strings? It looks like I can't access the "Contains" if I save them as ints.

Ultimately, I want to be able to use this as part of a query that accesses the Entity Framework and therefore passes the query as part of IQueryable <> to make sure that I don't return data when I want only handfull, for example:

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

Thus, any solution would be useful if query parameters (int array) via EF instead of receiving all the data and then checking them in memory.

Hurrah!

+6
source share
2 answers

but I really need to keep pouring identifiers into strings

Absolutely not. It's unclear what bars , but assuming it really should be orders , you can use:

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

or make a connection:

 var result = orders.Join(testArray, o => o.OrderId, id => id, (o, id) => o); 
+16
source

you can use the Intersect operator instead, why are you using arrays rather than lists? Code example:

  public class Order { public long OrderId { get; set; } public string Name { get; set; }} public class Rep { private List<Order> orders { get; set; } public void Q() { long[] testArray = {123, 456}; var res = orders.Intersect(orders); } } 
0
source

Source: https://habr.com/ru/post/918077/


All Articles