在下面的示例中,只有第1行到第4行包含所有列中的数据,其中第0行和第5行仅包含ID列中的数据。在dt2中,我只想添加第1行到第4行。所以我的问题是如何从我的LINQ查询中删除ID列?
提前感谢任何建设性的建议!
private void LoadDataTable()
{
DataTable dt1 = new DataTable();
//Create three columns
DataColumn dc = new DataColumn("ID", typeof(Int32));
dc.AutoIncrement = true;
dc.AllowDBNull = false;
dc.AutoIncrementSeed = 1;
dt1.Columns.Add(dc);
dc.SetOrdinal(0);
dc = new DataColumn("Item", typeof(String));
dt1.Columns.Add(dc);
dc = new DataColumn("Quantity", typeof(Int32));
dt1.Columns.Add(dc);
//Create items Array
string[] items = new string[] { "Ford", "Chevy", "GMC", "Buick", "Toyota", "Honda", "Mercury"
,"Hyundai", "Rolls Royce", "BMW", "Mercedes Benz", "Bentley", "Porche"
,"Infinity", "Jaguar" };
//Load Dummy data
Random rnd = new Random();
for (int i = 0; i < 5; i++)
{
DataRow dr = dt1.NewRow();
if (i > 0 && i < 4)
{
dr[1] = items[rnd.Next(i, items.Count())];
dr[2] = rnd.Next(i, 10000);
//Remove previously used Item from Array
items = items.Where(w => w != dr[1].ToString()).ToArray();
}
dt1.Rows.Add(dr);
}
//dt2 should only contain rows who have data in at least one column with the exception of the ID Column
DataTable dt2 = dt1.Rows.Cast<DataRow>()
.Where(w => w.ItemArray.Any(field => !string.IsNullOrEmpty(field.ToString().Trim()) && !(field is DBNull)))
.CopyToDataTable();
}
感谢Ivan Stoev
,这是解决方法 //dt2 should only contain rows who have data in at least one column with the exception of the ID Column
var columns = dt1.Columns.Cast<DataColumn>().Where(c => c.ColumnName != "ID").ToList();
DataTable dt2 = dt1.Rows.Cast<DataRow>()
.Where(w => columns.Select(c => w[c]).Any(field => !string.IsNullOrEmpty(field.ToString().Trim()) && !(field is DBNull)))
.CopyToDataTable();
答案 0 :(得分:1)
您需要使用其他ItemArray
值访问方法替换查询中的DataRow
,例如
var columns = dt1.Columns.Cast<DataColumn>().Where(c => c.ColumnName != "ID").ToList();
DataTable dt2 = dt1.Rows.Cast<DataRow>()
.Where(r => columns.Select(c => r[c]).Any(field => ...