2

主要的数据

Id Name
1 CENTRAL
2 EAST
3 EAST CENTRAL
4 EAST COASTAL
5 NORTH
6 NORTH WEST

7 南

8 中南部

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 SOUTH 0.0
8 SOUTH CENTRAL 0.0
9 WEST 0.0

请注意所有都是数据表我怎么能得到结果

4

1 回答 1

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 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;
    }
}

您可以DataTablequery以下语句中获取:

var result = query.ToDataTable();
于 2013-04-01T11:01:34.063 回答