查询数据表字段包含list< string>中的任何项目的行. [英] Query rows that the datatable field contain any item in the list<string>

查看:111
本文介绍了查询数据表字段包含list< string>中的任何项目的行.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是LINQ的新手.
我想查询描述列字符串(示例值今天我很幸运")包含/匹配List<string> lst中的任何项目的所有行.
例如,列表项包含{"lucky","bad","ok"}.
我想仅通过使用linq来实现,但我混淆了以下方法是否正确?
谢谢.

i'm new in LINQ.
I wanna query all rows that the description column string (example value "i am feeling lucky today.") contains/match any item in a List<string> lst.
Example the list items contain {"lucky", "bad", "ok" }.
I would like to achieve by using linq only, but I am confuse are below methods correct??
thanks.

选项1:
var item =
from a in datatbl.AsEnumerable()
from b in lst
where a.Field<string>("description").contains(b)
select a;

Option 1:
var item =
from a in datatbl.AsEnumerable()
from b in lst
where a.Field<string>("description").contains(b)
select a;

选项2:
var item =
from a in datatbl.AsEnumerable()
where lst.Any(x=> a.Field<string>("description").Contains(x))
select a;

Option 2:
var item =
from a in datatbl.AsEnumerable()
where lst.Any(x=> a.Field<string>("description").Contains(x))
select a;

推荐答案

您的两个选项都应该起作用(将包含"更改为包含").但是,如果您希望不区分大小写,则需要使用ToUpper之类的东西.

Both of your options should work (change contains to Contains). But if you want to be case-insensitive, you will need to use a ToUpper or something.

例如,此代码提供测试夹具"并处理不区分大小写的代码.

For example, this code provides a "test jig" and handles case insensitivity.

        DataTable datatbl = new DataTable();
        datatbl.Columns.Add(new DataColumn("description",typeof(string)));
        // add simple test rows
        datatbl.Rows.Add("I'm feeling lucky today.");
        datatbl.Rows.Add("I'm feeling bad today.");
        datatbl.Rows.Add("I'm feeling good today.");
        // more test rows here...
        List<string> lst = new List<string>(new string[] { "Lucky", "bad", "ok" });

        var item =
            from a in datatbl.AsEnumerable()
            from b in lst
            where a.Field<string>("description").ToUpper().Contains(b.ToUpper())
            select a;

        var item2 =
            from a in datatbl.AsEnumerable()
            where lst.Any(x => a.Field<string>("description").ToUpper().Contains(x.ToUpper()))
            select a;

这篇关于查询数据表字段包含list&lt; string&gt;中的任何项目的行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆