如何编写一个列中有多个值的LINQ查询?

gudnpqoy  于 2022-12-06  发布在  其他
关注(0)|答案(7)|浏览(188)

我需要从数据表中查找只包含一列多个值的数据。
下面是一个示例:

var Value = (from r in datatable.AsEnumerable()
             where r.Field<string>(ColumnName).Contains("test1,test2")
             select r ).ToList();

这里,ColumnName是我的Datatable的列名,“test1,test2”是不同的值(值的数量是动态的,并以“,”作为分隔符)。
我想做一个Linq查询,返回数据表中所有值等于“test1“和“test2“的记录。
编辑:以上LINQ查询返回的结果与以下SQL查询类似。Select * from Table where ColumnName in ('test1','test2')

cyvaqqii

cyvaqqii1#

使用Split + Join

IEnumerable<string> values = "test1,test2".Split(',');
var matchingRows = from row in datatable.AsEnumerable()
                   join value in values
                   on row.Field<string>(ColumnName) equals value
                   select row;
DataTable tblResult = matchingRows.CopyToDataTable(); // or ToList

为了完整性起见,less efficient采用Contains的方法反而更自然:

var matchingRows = from row in datatable.AsEnumerable()
                   where values.Contains(row.Field<string>(ColumnName))
                   select row;
mutmk8jj

mutmk8jj2#

构建列表:

var filters = new [] {"test1", "test2"};

var Value = (from r in datatable.AsEnumerable()
             where filters.Contains(r.Field<string>(ColumnName))
             select r ).ToList();

这将被转换成你想要的

Select * 
from Table 
where ColumnName in ('test1','test2')
kxe2p93d

kxe2p93d3#

试试这个:

var searchParameters = new []{ "test1", "test2" }; // or "test1,test2".Split(",")
var Value = (from r in datatable.AsEnumerable()
         where searchParameters.All(s => r.Field<string>(ColumnName).Contains(s))
         select r).ToList();
goucqfw6

goucqfw64#

你还是声明你可以“||“的

var Value = (from r in datatable.AsEnumerable()
                             where r.Field<string>(ColumnName).Contains(value1) || r.Field<string>(ColumnNamedatatable).Contains(value2)
                             select r).ToList();
chhqkbe1

chhqkbe15#

datatable.where(r=>{"test1","test2"}.Contains(r.ColumnName))
nnsrf1az

nnsrf1az6#

简单明了的方法是使用Select

范例:

var dt = new DataTable();
dt.Columns.Add("col1", typeof(string));
dt.Rows.Add(new object[] {"test1"});
dt.Rows.Add(new object[] {"test2"});
dt.Rows.Add(new object[] {"test3"});
dt.Rows.Add(new object[] {"test4"});

// Select * from Table where ColumnName in ('test1','test2')
var rows = dt.Select("col1 in ('test1','test2')");

rows现在是:

zfycwa2u

zfycwa2u7#

试试这个:

var Value = (from r in datatable.AsEnumerable()
                 where r.Field<string>(ColumnName).Contains("test1").Contains("test2")
                 select r ).ToList();

相关问题