我想使用LINQ获取数据行,并使用它们的值解析数据列名称。
因此,如果我有一个包含以下列和值的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);
}
}
答案 0 :(得分:1)
我认为您正在尝试获取列名称和行而不实际引用它们。这是你想要做的事情:
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);
}
}
答案 1 :(得分:0)
看看这是否能让你朝着正确的方向前进
编辑使用反射添加解决方案,因为这更符合您想要实现的目标
open $sh_script, ">", "$QSUB" or die "Can't open '$QSUB'";
print $sh_script "$cmd";
close $sh_script;
以下使用具有强类型属性的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
答案 2 :(得分:0)
我强烈建议映射到一个类,然后添加另一个结合它们的属性!