c# - Merge two DataTables with LINQ -
my question similar this
i have 2 datatables:
datatable 1:
column 1: date column 2: requests 1
datatable 2:
column 1: date column 2: requests 2
i need 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 did until now:
datatable lista_1 = ds.tables[0]; datatable lista_2 = ds.tables[1]; var mylinq = 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 return ilist collection (system.collections.ilist)
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
may have dates in list_1 there not in list_2 , vice versa, request need 0.
if need thing encapsulated in method, should create class returned:
public class dailyreport { public datetime date {get; set;} public int requests1 {get; set;} public int requests2 {get; set;} public int total // can calculated on fly { {return requests1 + requests2; } } }
and do
public list<dailyreport> getdailyreports(..parameters if needed...) { ... var mylinq = ... select new dailyreport { date = l1.field<datetime>("date"), requests1 = l1.field<int>("total"), requests2 = l2.field<int>("contagem"), }; return mylinq.tolist(); }
there dirty hacks enable return collection of anonymous objects, advise against it.
Comments
Post a Comment