我想使用LINQ获取一个数据row,并解析出数据列名及其值。
如果我有一个包含以下列和值的dataRow
DataColumn column1 with value '1'
DataColumn column2 with value 'ABC'
我想有一个字符串返回为"column1 = '1'和column2 = 'ABC'"
****代码不应该关心列名,也不应该关心表中的列数****
目的是过滤数据表,如:
var newRows = myTable.Select ("column1 = '1' and column2 = 'ABC'");
我可以像这样解析表的列:
string[] columnName = myTable.Columns.Cast<DataColumn>().Select(cn => cn.ColumnName).ToArray();
但是我还需要从目标行中提取值。感觉这可能是一个开始:
{
string[] columnNames = existingTable.Columns.Cast<DataColumn>().Select(cn => cn.ColumnName).ToArray();
foreach (DataRow oldRow in existingTable.Rows)
{
var criteria = string.Join("and", columnNames, oldRow.ItemArray);
}
}
我认为您试图获得列名和行,而不实际引用它们。这是你想要做的吗?
var table = new DataTable();
var column = new DataColumn {ColumnName = "column1"};
table.Columns.Add(column);
column = new DataColumn {ColumnName = "column2"};
table.Columns.Add(column);
var row = table.NewRow();
row["column1"] = "1";
row["column2"] = "ABC";
table.Rows.Add(row);
string output = "";
foreach (DataRow r in table.Rows)
{
output = table.Columns.Cast<DataColumn>()
.Aggregate(output, (current, c) => current +
string.Format("{0}='{1}' ", c.ColumnName, (string) r[c]));
output = output + Environment.NewLine;
}
// output should now contain "column1='1' column2='ABC'"
您也可以在此基础上创建扩展方法,这些方法可以在DataTable
(所有行)或DataRow
(单行)上操作:
public static class Extensions
{
public static string ToText(this DataRow dr)
{
string output = "";
output = dr.Table.Columns.Cast<DataColumn>()
.Aggregate(output, (current, c) => current +
string.Format("{0}='{1}'", c.ColumnName, (string)dr[c]));
return output;
}
public static string ToText(this DataTable table)
{
return table.Rows.Cast<DataRow>()
.Aggregate("", (current, dr) => current + dr.ToText() + Environment.NewLine);
}
}
我强烈建议映射到一个类,然后添加另一个将两者结合起来的属性!
看看这是否能帮你找到正确的方向
EDIT添加了使用反射的解决方案,因为这更符合您想要完成的任务
void Main()
{
List<MyClass> myColl = new List<MyClass>() { new MyClass() { myFirstProp = "1", mySecondProp = "ABC" } };
foreach (MyClass r in myColl)
{
List<string> rPropsAsStrings = new List<string>();
foreach (PropertyInfo propertyInfo in r.GetType().GetProperties())
{
rPropsAsStrings.Add(String.Format("{0} = {1}", propertyInfo.Name, propertyInfo.GetValue(r, null)));
}
Console.WriteLine(String.Join(" and ", rPropsAsStrings.ToArray()));
}
}
public class MyClass
{
public string myFirstProp { get; set; }
public string mySecondProp { get; set; }
}
下面使用具有强类型属性的Linq
System.Data.DataTable table = new DataTable("ParentTable");
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = typeof(string);
column.ColumnName = "column1";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = typeof(string);
column.ColumnName = "column2";
table.Columns.Add(column);
row = table.NewRow();
row["column1"] = "1";
row["column2"] = "ABC";
table.Rows.Add(row);
var results = from myRow in table.AsEnumerable()
select String.Format("column1 = {0}, column2 = {1}", myRow[0], myRow[1]);
foreach (string r in results)
{
Console.WriteLine(r);
}