簡體   English   中英

使用LINQ合並兩個數據表

[英]Merge two DataTables with LINQ

我的問題也是類似THIS

我有兩個數據表:

數據表1:

Column 1: Date
Column 2: Requests 1

數據表2:

Column 1: Date
Column 2: Requests 2

我需要以下結果:

新數據表:

Column 1: Date
Column 2: Requests 1
Column 3: Requests 2

預期結果:

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

到目前為止,我所做的是:

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

我想返回一個IList集合(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; }
}

更新2

List_1中的日期可能沒有List_2中的日期,反之亦然,因此“請求”必須為0。

如果需要將此東西封裝在方法中,則應創建一個要返回的類:

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

然后做

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

有一些骯臟的技巧可以使您返回匿名對象的集合,但是我建議您不要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM