简体   繁体   English

LINQ查询不返回字符串比较中的行

[英]LINQ query not returning rows in string comparison

I'm new to writing LINQ queries, and I'm having trouble with string comparisons. 我刚开始编写LINQ查询,但是在字符串比较方面遇到了麻烦。 I'm loading the data into a DataTable (confirmed that table in SQL DB and DataTable have same number of rows), but for some reason I can't find a value that I know exists in both. 我正在将数据加载到DataTable中(确认SQL DB和DataTable中的表具有相同的行数),但是由于某种原因,我找不到两者都存在的值。

The text box contains 'servername' while the datarows contain 'servername.mydomain.net', so here's what my code looks like 文本框包含“服务器名称”,而数据行包含“服务器名称.mydomain.net”,所以这是我的代码的样子

string strParameter = txtAutoComplete.ToString().ToLower();

    //WUG TableAdapter and DataTable
    dsCIInfoTableAdapters.DeviceTableAdapter taWUG;
    taWUG = new dsCIInfoTableAdapters.DeviceTableAdapter();

    dsCIInfo.DeviceDataTable dtWUG = new dsCIInfo.DeviceDataTable();
    taWUG.Fill(dtWUG);

    var qstWUG = (from row in dtWUG.AsEnumerable()
                  where row.Field<string>("sDisplayName").ToLower().Contains(strParameter)
                  select row.Field<string>("sDisplayName"));

Beleive in your LINQ statement dtWUG needs to be dtWUG.AsEnumerable(). 在您的LINQ语句中保持沉默dtWUG需要为dtWUG.AsEnumerable()。 Linq only works on data sources that implement the IEnumerable Interface. Linq仅适用于实现IEnumerable接口的数据源。

You can debug it easier if you add some let statements where you can add breakpoints: 如果添加一些let语句可以在其中添加断点,则可以更轻松地进行调试:

    var qstWUG = (from row in dtWUG
                  let display = row.Field<string>("sDisplayName")
                  let lower = display.ToLower()
                  let contains = lower.Contains(strParameter)
                  where contains
                  select display).ToArray();

Also convert it to an array using .ToArray() at the end, will make it execute immediately (LINQ is lazy by paradigm, doesn't execute until it's needed), and also easier to look at in subsequent breakpoints. 最后还要使用.ToArray()将其转换为数组,使它立即执行(LINQ被范式懒惰,直到需要时才执行),并且在以后的断点处更容易查看。

Yeah, I feel stupid... I forgot to use the textbox.text to assign it to a string 是的,我很愚蠢...我忘记了使用textbox.text将其分配给字符串

string strParameter = txtAutoComplete.Text.ToLower();


        //WUG TableAdapter and DataTable
        dsCIInfoTableAdapters.DeviceTableAdapter taWUG;
        taWUG = new dsCIInfoTableAdapters.DeviceTableAdapter();

        dsCIInfo.DeviceDataTable dtWUG = new dsCIInfo.DeviceDataTable();
        taWUG.Fill(dtWUG);

        var qstWUG = (from row in dtWUG.AsEnumerable()
                      let display = row.Field<string>("sDisplayName")
                      where display.ToLower().Contains(strParameter)
                      select display).ToArray();

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

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