简体   繁体   English

LINQ查询,其中where条件包含

[英]LINQ query with a where condition containing

I am just learning LINQ and I have come across and issue Im not sure how to do in LINQ. 我只是在学习LINQ,遇到了问题,我不确定该如何在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). 我只想选择数据库中数字位于“ 1、3、4、5”的行列表​​中的行(这些数字仅是示例)。

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. 在SQL的DASHBAORDFIGURES表中,我有2条记录,其中网点号= 1,因此应该提供2条记录。 Sorry if this is a simple thing, its just new to me and its frustrating. 很抱歉,如果这是一件简单的事情,对我来说这只是新事物,而且令人沮丧。

You can use Contains as tagged: 您可以使用Contains作为标记:

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()) . 但是列numberintList<string>存储字符串,也许您的LINQ提供程序不支持.Contains(figure.ToString()) Then convert the strings to int first: 然后首先将字符串转换为int:

List<int> outletsNeededList = outletsNeeded.Select(int.Parse).ToList();

The answer that Tim provided is one method. 蒂姆提供的答案是一种方法。 Linq and lambda are interchangeable. Linq和lambda是可互换的。 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 还请查看以下内容,因为它提供了与您所寻找的解决方案非常相似的解决方案: 链接

As per i understand, you want to fetch data in similar way as IN (SQL) clause does it. 据我了解,您希望以类似于IN(SQL)子句的方式获取数据。

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. Linq +任何编程语言都更加灵活。 You can build a list of integers ( List ) to build query. 您可以构建一个整数列表List )来构建查询。

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 马切伊

Thank you all iv now got it to work using all your suggestions 谢谢大家iv现在可以使用您的所有建议进行工作

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. 再次感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM