假设您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 to 对象获得所需的内容:
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();