0

I am just learning LINQ and I have come across and issue Im not sure how to do in LINQ.

string numbers = "1,3,4,5";
string[] outletsInaStringArray = outlets.Split(',');
List<string> numbersAsAList = outletsInaStringArray.ToList();

I have a field in my database which holds a number. I only want to select the lines WHERE the number in the database is IN the line list of numbers "1,3,4,5" (these numbers are just examples).

Thanks in advance


I have looked at Tim and James answers and also looked at the line that James has sent. Im still a bit confused.....Sorry. Below is my actual code. It compiles but does not work

string outlets = "1,3,4,5"
string[] outletsNeeded = outlets.Split(',');
List<string> outletsNeededList = outletsNeeded.ToList();

DashboardEntities1 db = new DashboardEntities1();
var deptSalesQuery =  (
from d in db.DashboardFigures
where (d.TypeOfinformation == "DEPTSALES") && (outletsNeeded.ToString().Contains(d.OutletNo.ToString())) 
                                     select new DeptSales
                                     {
                                          Dn = (int)d.Number,
                                          Dnm = "Mens",
                                          On  = d.OutletNo,
                                          Qs = (double)d.Value_4,
                                          Se = (double)d.Value_2,
                                          Si = (double)d.Value_3
                                     }                                    
                                 );

In the DASHBAORDFIGURES table in SQL I have 2 records where the outlets number = 1, and therefore should have come up with two records. Sorry if this is a simple thing, its just new to me and its frustrating.

Alpesh
  • 31
  • 1
  • 10
  • `ToString()` is not supported by `Linq-To-Entities`. Rather convert the string list to integer list and use `Contains`. – Mat J Jan 05 '15 at 07:12

4 Answers4

2

You can use Contains as tagged:

var query = db.Table
    .Where(x => outletsInaStringArray.Contains(x.Number) && x.information == "SALES");

that was method syntax, if you prefer query syntax:

var query = from figure in db.Figures
            where outletsInaStringArray.Contains(figure.number)
              &&  figure.information == "SALES"
            select figure;

But the column number is int, the List<string> stores strings, maybe your LINQ provider does not support .Contains(figure.ToString()). Then convert the strings to int first:

List<int> outletsNeededList = outletsNeeded.Select(int.Parse).ToList();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Hi Tim, Thanks for that, how would I use this in the LINQ statement below. – Alpesh Jan 03 '15 at 23:03
  • var salesQuery = (from d in db.Figures where (d.information == "SALES") && (WHERE d.number is in the list "1,3,4,5") select {....} – Alpesh Jan 03 '15 at 23:04
  • @TimSchmelter: Probably tack on the additional constraint on the linq as well. – James Shaw Jan 03 '15 at 23:18
  • @TimSchmelter just seen your answer while I have editing my question. ill give it a try. Thanks – Alpesh Jan 03 '15 at 23:32
  • where d.TypeOfinformation == "DEPTSALES" && d.OutletNo.Contains(outletsNeeded) gives me the following error> Error 1 Instance argument: cannot convert from 'int' to 'System.Linq.IQueryable'AND Error 2 'int' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource)' has some invalid argument – Alpesh Jan 03 '15 at 23:52
  • @Alpesh: just use our code. You are using `outletsNeeded.ToString().Contains` which is pointless since `array.ToString()` just returns the name of the type. You just need `outletsNeeded.Contains`. The collection is `outletsNeeded`, the single value is `figure.number`. – Tim Schmelter Jan 03 '15 at 23:52
  • @TimSchmelter Put in the code in the way you mentioned but Im getting compile error. – Alpesh Jan 03 '15 at 23:55
  • @TimSchmelter The problem seems to be his `outletsNeeded` is a `List` and his database field `d.OutletNo` is number. You cannot use `Contains` in such situations and `ToString` is not supported by the provider. – Mat J Jan 05 '15 at 07:16
  • @Mathew: in that case he should use `List outletsNeededList = outletsNeeded.Select(int.Parse).ToList();` – Tim Schmelter Jan 05 '15 at 08:25
  • @Alpesh: have a look at the last comments and my edit. – Tim Schmelter Jan 05 '15 at 08:28
0

The answer that Tim provided is one method. Linq and lambda are interchangeable. Have a look at the following posting as well. Link

var result = from x in db.Table.ToList()
             where outletsInaStringArray.Contains(x.Number)
             select x;

Also have a look the following as it offers a very similar solution to the one you are looking for: Link

Community
  • 1
  • 1
James Shaw
  • 839
  • 1
  • 6
  • 16
0

As per i understand, you want to fetch data in similar way as IN (SQL) clause does it.

SELECT <Field_List>
FROM Table
WHERE IntegerField IN (1,2,4,5)

But i'm wondering why do you want to do it that way, when you can join data and get only matches. The worse is that you're trying to mix different data type and pass comma delimited text as a set of integers (i may be wrong):

SELECT <Field_List>
FROM Table
WHERE IntegerField IN ("1,2,4,5")

Above query won't execute, because the set of integers is "packed" into comma delimited string. To be able to execute that query, a conversion between data types must be done. Numbers in a string have to be converted to a set of integers (using user define split function or Common Table Expression):

;WITH CTE AS
(
     --here convertion occurs
)
SELECT t2.<Field_List>
FROM CTE As t1 INNER JOIN TableName AS t2 ON t1.MyNumber = t2.IntegerField 

Linq + any programming language is more flexible. You can build a list of integers (List) to build query.

See simple example:

void Main()
{

    List<MyData> data = new List<MyData>{
                    new MyData(1,10),
                    new MyData(2, 11),
                    new MyData(5, 12),
                    new MyData(8, 13),
                    new MyData(12, 14)
                    };

    //you're using comma delimited string 
    //string searchedNumbers = "1,3,4,5";
    //var qry = from n in data 
    //      join s in searchedNumbers.Split(',').Select(x=>int.Parse(x)) on n.ID equals s 
    //      select n;
    //qry.Dump();

    List<int> searchedNumbers = new List<int>{1,2,4,5};
    var qry = from n in data 
            join s in searchedNumbers on n.ID equals s 
            select n;
    qry.Dump();

}

// Define other methods and classes here
class MyData
{
    private int id = 0;
    private int weight = 0;

    public MyData(int _id, int _weight)
    {
        id = _id;
        weight = _weight;
    }

    public int ID
    {
        get{return id;}
        set {id = value;}
    }

    public int Weight
    {
        get{return weight;}
        set {weight = value;}
    }
}

Result:

ID  Weight
1   10 
5   12 

Cheers
Maciej

Maciej Los
  • 8,468
  • 1
  • 20
  • 35
0

Thank you all iv now got it to work using all your suggestions

the final code that works is as follows

DeptSales myDeptSales = new DeptSales();                  // Single department
List<DeptSales> myDeptSalesList = new List<DeptSales>();  // List of Departments
DashboardEntities1 db = new DashboardEntities1();

var deptSalesQuery = from d in db.DashboardFigures
join s in outlets.Split(',').Select(x => int.Parse(x)) on d.OutletNo equals s
where (d.TypeOfinformation == "DEPTSALES")
select new DeptSales
                   {
                    Dn = (int)d.Number,
                    Dnm = "Mens",
                    On = d.OutletNo,
                    Qs = (double)d.Value_4,
                    Se = (double)d.Value_2,
                    Si = (double)d.Value_3
                    };

Thanks once again.

Alpesh
  • 31
  • 1
  • 10