2017-08-21 21 views
2

見ての通り、私は最高の日付と最新のレコードとグループを取得 - LINQ

AccoundID | Group | DateOfBill 
1234  | A  | 2017-07-12 
1234  | B  | 2017-07-16 
1234  | C  | 2017-07-31 
1235  | A  | 2017-07-31 
1236  | B  | 2017-07-31 

以下のように表Billingを持って、AccountID 1234年7月2017年に3取引を行っているので、私はAccountID 1234必見リストが必要Group Cである必要があります。これは、そのトランザクションの最新の日付であるためです。

は、ここに私のコードスニペット

var LatestAccount = from n in Billing 
        where (n.Group == "A" || n.Group == "B" || n.Group == "C") 
        group n by new { n.AccountID, n.Group } into g 
        select new { 
         AccountId = g.Key.AccountID, 
         Group = g.Key.Group , 
         DateOfBill = g.Max(t => t.DateOfBill) 
        }; 

ですが、結果は間違っています。 LINQのやり方は?

+0

アカウントIDとグループでグループ化しています。ユースケースのアカウントIDでグループ化するだけです –

+0

最終結果の表示方法を投稿してください。 –

答えて

2
class Program 
{ 
    static void Main(string[] args) 
    { 
     List<Billing> Billings = new List<Billing>() 
     { 
      new Billing() 
      { 
       AccountID = 1234, DateOfBill = new DateTime(2017,07,12), Group = "A" 

      }, 
      new Billing() 
      { 
       AccountID = 1234, DateOfBill = new DateTime(2017,07,16), Group = "B" 

      }, 
      new Billing() 
      { 
       AccountID = 1234, DateOfBill = new DateTime(2017,07,31), Group = "C" 

      }, 
      new Billing() 
      { 
       AccountID = 1235, DateOfBill = new DateTime(2017,07,31), Group = "A" 

      }, 
      new Billing() 
      { 
       AccountID = 1236, DateOfBill = new DateTime(2017,07,31), Group = "B" 

      }    
     }; 

     var LatestAccount = from n in Billings 
          where (n.Group == "A" || n.Group == "B" || n.Group == "C") 
          group n by new { n.AccountID } into g 
          select g.Where(d => d.DateOfBill == g.Max(m => m.DateOfBill)).Select(x => new { AccountId = g.Key.AccountID, Group = x.Group, DateOfBill = x.DateOfBill }).FirstOrDefault(); 

     foreach (var item in LatestAccount) 
     { 
      Console.WriteLine("AccountID: " + item.AccountId + " Date of Bill: " + item.DateOfBill + " Group: "+ item.Group); 
     } 
     Console.ReadLine(); 
    } 
} 
class Billing 
{ 
    public int AccountID { get; set; } 
    public string Group { get; set; } 
    public DateTime DateOfBill { get; set; } 
} 

希望の出力を表示すると、自分の答えを変更できます。

enter image description here

+0

はい、これは私が探しているものです – Chuki2

+0

あなたのために働いていれば、正解として私の返事を受け入れてください - 他のユーザーには、回答がうまくいくことを知り、質問にAnsweredというマークを付けることができます。 私の答えがあなたのために働いたのか、それとも答えに問題があるのか​​教えてください。 –

関連する問題