我是 LINQ 的新手,所以我确定我的以下逻辑有错误。
我有一个对象列表:
class Characteristic
{
public string Name { get; set; }
public string Value { get; set; }
public bool IsIncluded { get; set; }
}
使用列表中的每个对象,我想在 LINQ 中构建一个以 DataTable
开头的查询,并根据对象值过滤它,并生成一个 DataTable
作为结果。
到目前为止我的代码:
DataTable table = MyTable;
// Also tried: DataTable table = MyTable.Clone();
foreach (Characteristic c in characteristics)
{
if (c.IsIncluded)
{
var q = (from r in table.AsEnumerable()
where r.Field<string>(c.Name) == c.Value
select r);
table = rows.CopyToDataTable();
}
else
{
var q = (from r in table.AsEnumerable()
where r.Field<string>(c.Name) != c.Value
select r);
table = q.CopyToDataTable();
}
}
更新
我在慌乱中犯了一个错误;我的 DataTable
不是空的,我只是忘了将它绑定(bind)到 DataGrid
。而且,Henk Holterman 指出我在每次迭代时都覆盖了我的结果集,这是一个逻辑错误。
Henk 的代码目前看来效果最好,但我需要做更多测试。
Spinon 的回答也帮助我理清思路,但他的代码给了我一个错误。
我需要尝试更好地理解 Timwi 的代码,但以目前的形式,它对我不起作用。
新代码
DataTable table = new DataTable();
foreach (Characteristic c in characteristics)
{
EnumerableRowCollection<DataRow> rows = null;
if (c.IsIncluded)
{
rows = (from r in MyTable.AsEnumerable()
where r.Field<string>(c.Name) == c.Value
select r);
}
else
{
rows = (from r in MyTable.AsEnumerable()
where r.Field<string>(c.Name) != c.Value
select r);
}
table.Merge(rows.CopyToDataTable());
}
dataGrid.DataContext = table;
最佳答案
您发帖的逻辑很奇怪;这是我认为您正在努力实现的尝试。
DataTable table = MyTable.AsEnumerable()
.Where(r => characteristics.All(c => !c.IsIncluded ||
r.Field<string>(c.Name) == c.Value))
.CopyToDataTable();
如果你真的想在你的帖子中使用逻辑,将 ||
更改为 ^
,但这似乎没有什么意义。
关于c# - LINQ 查询不返回任何行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4672666/