0

I have the following items in a list:

Date          Amount    AnId     AnotherId    MainDate
2013/01/10    1000      1        5            2013/01/12
2013/01/11    2000      2        5            2013/01/12
2013/01/15    4000      1        5            2013/01/12

I want to use linq to return the following:

Date          Amount    AnId     AnotherId    MainDate
2013/01/11    2000      2        5            2013/01/12
2013/01/15    4000      1        5            2013/01/12

i.e. for a specific MainDate, I only want the latest items that are unique across AnId and anotherId. So, the item on 2013/01/10 is removed as there is an item for the same MainDate, AnId and AnotherId that has a date that is later than the items date...

I've been trying to Group By MainDate and Then By AnId and AnotherId and OrderByDescending and then select the first item for each group, but not too clued up on linq, so i'm struggling...

Bazzz
  • 26,427
  • 12
  • 52
  • 69
newbie_86
  • 4,520
  • 17
  • 58
  • 89
  • Please add you C#/VB code with the Linq and lambdas that you have tried and didn't get the result you were hoping for. It's then easier for us to see where it went wrong. – Bazzz Jan 24 '13 at 07:57
  • possible duplicate of [Group By Multiple Columns](http://stackoverflow.com/questions/847066/group-by-multiple-columns) – nawfal Jan 28 '14 at 23:10

2 Answers2

3

Use the same anonymous type in the dot notation that you do in the query expression:

var qry = cust.GroupBy(cm => new { cm.MainDate, cm.AnId ,  cm.AnotherId })

Refer:
How to Group By multiple columns in LINQ ?
LINQ Group By Multiple fields -Syntax help

Community
  • 1
  • 1
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
  • thanks! how would this get me the item with the latest date? also if i group as above, how do i get my objects to be of my initial type? e.g. they're of type MyClass, after grouping, i still want them to be of type MyClass, just filtered... – newbie_86 Jan 24 '13 at 08:12
  • what will you get if you use .orderby(cm=>cm.Date).GroupBy(..), then fetch the first element of first group from the result, that may be your latest element.. – Niranjan Singh Jan 24 '13 at 08:16
  • I have something like this : var test = containerList.OrderByDescending(t => t.Date).GroupBy(g => new { g.MainDate, g.AnId, g.AnotherId }). ToList(); The problem I now have is how to select the data for each item? i.e. I want the amount for each grouping (not summed)... – newbie_86 Jan 24 '13 at 08:33
  • check the reference links they should help you. – Niranjan Singh Jan 24 '13 at 09:17
0

using lambda expressions you can write

.GroupBy(e=>new { MainDate = e.MainDate, Id = e.AnId})
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80