[英]Merge two DataTables with LINQ
My question is similar too THIS 我的问题也是类似THIS
I have two DataTables: 我有两个数据表:
DataTable 1: 数据表1:
Column 1: Date
Column 2: Requests 1
DataTable 2: 数据表2:
Column 1: Date
Column 2: Requests 2
I need the bellow result: 我需要以下结果:
New DataTable: 新数据表:
Column 1: Date
Column 2: Requests 1
Column 3: Requests 2
Expected Result: 预期结果:
Date Requests 1 Requests 2 Total
15/08/2013 25 40 60
14/08/2013 40 60 100
13/08/2013 40 0 25
12/08/2013 0 80 80
What I did until now: 到目前为止,我所做的是:
DataTable Lista_1 = ds.Tables[0];
DataTable Lista_2 = ds.Tables[1];
var myLINQ = from l1 in Lista_1.AsEnumerable()
join l2 in Lista_2.AsEnumerable()
on l1.Field<DateTime>("Date") equals l2.Field<DateTime>("Date")
select new
{
dateRelatorio = l1.Field<DateTime>("Date"),
request1Relatorio = l1.Field<int>("Total"),
request2Relatorio = l2.Field<int>("contagem"),
total = l1.Field<int>("Total") + l2.Field<int>("contagem")
};
And I would like to return an IList collection (System.Collections.IList) 我想返回一个IList集合(System.Collections.IList)
UPDATE UPDATE
listReturn = new List<Stats>();
public class Stats
{
public DateTime dateRelatorio { get; set; }
public int request1Relatorio { get; set; }
public int request2Relatorio { get; set; }
public int total { get; set; }
}
UPDATE 2 更新2
May have dates in List_1 that there is not in List_2 and vice versa, so the Request need to be 0. List_1中的日期可能没有List_2中的日期,反之亦然,因此“请求”必须为0。
If you need this thing to be encapsulated in a method, you should create a class to be returned: 如果需要将此东西封装在方法中,则应创建一个要返回的类:
public class DailyReport
{
public DateTime Date {get; set;}
public int Requests1 {get; set;}
public int Requests2 {get; set;}
public int Total // this can be calculated on the fly
{
get {return Requests1 + Requests2; }
}
}
And then do 然后做
public List<DailyReport> GetDailyReports(..parameters if needed...)
{
...
var myLINQ = from ...
select new DailyReport {
Date = l1.Field<DateTime>("Date"),
Requests1 = l1.Field<int>("Total"),
Requests2 = l2.Field<int>("contagem"),
};
return myLINQ.ToList();
}
There are some dirty hacks that could enable you to return an collection of anonymous objects, but I would advise against it. 有一些肮脏的技巧可以使您返回匿名对象的集合,但是我建议您不要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.