我是 LINQ 的新手,所以我确信下面的逻辑有错误。
我有一个对象列表:
class Characteristic
{
public string Name { get; set; }
public string Value { get; set; }
public bool IsIncluded { get; set; }
}
使用列表中的每个对象,我想在 LINQ 中构建一个以 a 开头的查询DataTable
,并根据对象值对其进行过滤,并产生 aDataTable
作为结果。
到目前为止我的代码:
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
的不是空的,我只是忘记将它绑定到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;