0

I'm trying to select a number DataRows with only specified fields from a Linq query, and then use these DataRows to populate a DataTable. The problem is that when I add these DataRows to the new DataTable I'm expect both ID and Name field to be populated respectively. However, the ID field in the DataTable contains both ID and Name values. Can someone point out what I'm doing wrong.

Here's the code:

var query2 = from s in Tables[Table_Sec].AsEnumerable()
             where query.Contains(s["sectype"])
             select new { id = s["id"], name = s["name"] }; // I only want these fields



DataTable dt = new DataTable();  // Create my new dataTable
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("name", typeof(string));

foreach(var row in query2)
{
  dt.Rows.Add(row);  // ID field contains both ID and Name strings. Name field contains nothing
}
4

5 回答 5

1

您可以尝试这样做,因为 DataRow 构造函数允许您传递对象数组

var result = from s in Tables[Table_Sec].AsEnumerable()
             where query.Contains(s["sectype"])
             select new object[] 
             {
                 s["id"],
                 s["name" ]
             };

DataTable dt = new DataTable();  
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("name", typeof(string));

foreach(var row in result)
{
    dt.Rows.Add(row); 
}

// 编辑:
我不推荐这种方式,因为它在很大程度上取决于列的正确顺序,我什至不确定是否还有其他情况会导致混乱=)从其他解决方案中选择一个(至少用于编码)

于 2013-02-26T16:43:21.513 回答
0

我会避免使用此方法的数据表并使用 POCO,Plain Old Class Object。

public class POCO
{
     public string id { get; set; }
     public string name { get; set; }
}

var query2 = from s in Tables[Table_Sec].AsEnumerable()
             where query.Contains(s["sectype"])
             select new POCO { id = s["id"], name = s["name"] };

POCO 的优点是您将数据与现有事物的关联分开,而是将其引用到仅作为集合而存在的类。

于 2013-02-26T16:35:16.630 回答
0

来自MSDN

DataRow newCustomersRow = dataSet1.Tables["Customers"].NewRow();

newCustomersRow["CustomerID"] = "ALFKI";
newCustomersRow["CompanyName"] = "Alfreds Futterkiste";

dataSet1.Tables["Customers"].Rows.Add(newCustomersRow);

这是向数据表添加行的方式

所以你的会是这样的:

foreach(var row in query2)
{
var newRow = dt.NewRow();
newRow["id"] = row.id;
newRow["name"] = row.name;
  dt.Rows.Add(newRow);  // ID field contains both ID and Name strings. Name field contains nothing
}
于 2013-02-26T16:34:05.740 回答
0

您必须手动填充一行中的每个单元格:

foreach(var row in query2)
{
    var newRow = dt.NewRow();
    newRow["id"]= row.id;
    newRow["name"]= row.name;
    dt.Rows.Add(newRow);
}
于 2013-02-26T16:34:39.620 回答
0

你没有很好地描述这个问题。但是,您不应将行添加到不同的行,DataTables因为您通常会遇到异常(“行已属于另一个表”)。

您应该使用强类型字段扩展方法,以确保您ReferenceEquals在选择对象时不会误用。当CopyToDataTableLinqDataTable查询包含IEnumerable<DataRow>.

出于性能原因,我也会使用Enumerable.Join而不是:query.Contains

var query2 = from secRow in Tables[Table_Sec].AsEnumerable()
             join sectype in query on secRow.Field<string>("sectype") equals sectype 
             select secRow;

DataTable dt = query2.CopyToDataTable();
于 2013-02-26T16:41:47.993 回答