Id名称
1中央
2 EAST
3 EAST CENTRAL
4东海岸
5北
6西北
7南
8 SOUTH CENTRAL
9西
Id名称值
1 CENTRAL 125.65
5 NORTH 553.21
Id名称值
1 CENTRAL 125.65
2 EAST 0.0
3 EAST CENTRAL 0.0
4 EAST COASTAL 0.0
5 NORTH 553.21
6 NORTH WEST 0.0
7南0.0
8 SOUTH CENTRAL 0.0
9 WEST 0.0
请注意所有数据表是如何获得结果的
答案 0 :(得分:2)
请说明您的DataTable
声明如下:
var dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("Id", typeof(int)));
dt1.Columns.Add(new DataColumn("Name", typeof(string)));
var dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("Id", typeof(int)));
dt2.Columns.Add(new DataColumn("Name", typeof(string)));
dt2.Columns.Add(new DataColumn("Value", typeof(double)));
您可以加入它并通过LINQ到对象获得您想要的内容:
var query = from r1 in dt1.AsEnumerable()
join r2 in dt2.AsEnumerable() on r1.Field<int>("Id") equals r2.Field<int>("Id") into r3
from r4 in r3.DefaultIfEmpty()
select new
{
Id = r1.Field<int>("Id"),
Name = r1.Field<string>("Name"),
Value = r4 == null ? 0.00 : r4.Field<double>("Value")
};
使用IEnumerable<Anonymous_Type>
,您可以使用DataTable
扩展方法返回ToDataTable<T>
个对象:
public static class EnumerableToDataTableConverter
{
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var newRow = dataTable.NewRow();
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
newRow[Props[i].Name] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(newRow);
}
//put a breakpoint here and check datatable
return dataTable;
}
}
您可以通过以下声明从DataTable
获取query
:
var result = query.ToDataTable();