1

我是 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;
4

3 回答 3

3

您发帖的逻辑很不稳定;这是我对我认为你正在努力实现的目标的尝试。

DataTable table = MyTable.AsEnumerable()
     .Where(r => characteristics.All(c => !c.IsIncluded ||
                                          r.Field<string>(c.Name) == c.Value))
     .CopyToDataTable();

如果您真的想在发帖中使用逻辑,请更改||^,但这似乎没有什么意义。

于 2011-01-12T19:00:46.070 回答
1

你覆盖了table每个特征的变量,所以最后它只保存上一轮的结果,这显然是空的。

你可以做的是这样的:

// untested
var t = q.CopyToDataTable();
table.Merge(t);

我怀疑您的查询应该使用 MyTable 作为源:

var q = (from r in MyTable.AsEnumerable() ...

但这并不完全清楚。

于 2011-01-12T18:52:04.747 回答
1

如果您只是尝试将行插入表中,请尝试以这种方式调用 CopyToDataTable 方法:

q.CopyToDataTable(table, LoadOption.PreserveChanges);

这样,您无需重新分配表变量,只需使用要插入的新行来更新它。

编辑:这是我所说的一个例子:

DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Value", typeof(string));
于 2011-01-12T18:58:28.260 回答