0

SQL Query

SELECT *
FROM tblOrders 
WHERE CustomerId in (3455,4423,7655,1000)

LINQ Query ?

Say, I have an Array of IDs, then how do I search?

int[4] _ids;

_ids[0]=3455
_ids[1]=4423
_ids[2]=7655
_ids[3]=1000

 var _orders = (from o in tblOrders 
                where (o.CustomerId in _ids[])
                select o);

Above code is just for the example sake, I know it's wrong. But, is this possible?

Guge
  • 4,569
  • 4
  • 35
  • 47
Ravi
  • 297
  • 1
  • 5
  • 19
  • http://stackoverflow.com/questions/1075540/linq-to-sql-how-to-do-where-column-in-list-of-values –  May 08 '14 at 08:01
  • Can you please clarify why -1 because same thing is in accepted answer "lstOrders.FindAll(x => _customers.Any(y =>y == x.CustomerID))".Rest code i placed is just to fill dummy lists for better explaining your example and that could be removed if not required. – Gaurav Rajput May 15 '14 at 12:51

3 Answers3

0

No, it is not.

Try this one:

var _orders = from o in tblOrders 
              where _ids.Contains(o.CustomerId)
              select o;

The keyword in you used, it is used for other purpose in C#. It is not like IN in SQL. It is used in foreach statements. For instance:

foreach(var _id in _ids)
    Console.WriteLine(_id);

Also, it is used as a generic modifier, for generic type parameters. For more documentation on the latter, please have a look here.

Christos
  • 53,228
  • 8
  • 76
  • 108
0

You can use the Contains method of the _ids array.

var _orders = from o in tblOrders
              where _ids.Contains(o.CustomerId)
              select o;
rtlayzell
  • 608
  • 4
  • 20
-1

Use code as given below

        List<Orders> lstOrders = new List<Orders>();
        Orders objOrders;
        for (int index = 1; index <= 10; index++)
        {
            objOrders = new Orders();
            objOrders.OrderID = index;
            objOrders.Order = "Order_" + index.ToString();
            objOrders.CustomerID = index;
            lstOrders.Add(objOrders);
        }


        int[] _customers = { 1, 2, 3, 4, 5 };
        List<Orders> lstFilteredOrders = new List<Orders>();
        lstFilteredOrders.AddRange(lstOrders.FindAll(x => _customers.Any(y =>y == x.CustomerID)));
Gaurav Rajput
  • 617
  • 5
  • 8