10

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!

3
  • 3
    This is the kind of things I do with EF... var orders = _repo.Orders().Where(i => orderArray.Contains(i.OrderId)); seems good to me. What's the problem exactly? Commented Jun 14, 2012 at 9:49
  • @Kek: I don't think you can use local lists/arrays when querying EF Commented Jun 14, 2012 at 9:54
  • 2
    mmm I'd say you can. The list will be enumered and transformed to a list of (id=Cste) OR ... I don't see the problem Commented Jun 14, 2012 at 9:56

2 Answers 2

21

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);
Sign up to request clarification or add additional context in comments.

1 Comment

not sure why it didn't work when I did this first time. thanks for your answer
0

you can use the Intersect operator instead, why do you use arrays and not 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);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.