我是LINQ的新手,所以我確信在我的邏輯中有一個錯誤。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();
}
}
UPDATE
我是在一個恐慌趕時間,我犯了一個錯誤;我的DataTable
不是空的,我忘了將它綁定到DataGrid
。但是,Henk Holterman指出,我每次迭代都覆蓋了我的結果集,這是一個邏輯錯誤。
亨克的代碼似乎工作到目前爲止最好,但我需要做更多的測試。
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;
我想覆蓋它,因爲我想應用* ALL *過濾器。即使在第一次迭代之後,表格也顯示爲空。這也是我選擇爲這個代碼塊創建一個新的`DataTable`引用的原因。 – JohnB 2011-01-12 18:56:09