简体   繁体   中英

Merge two DataTables with LINQ

My question is similar too THIS

I have two DataTables:

DataTable 1:

Column 1: Date
Column 2: Requests 1

DataTable 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)

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 that there is not in List_2 and vice versa, so the Request need to be 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM