1

We have a list of data in a specific class:

public string id { get; set; }
public string date { get; set; }

What is the best way to group the list by date? For example, we have a list of 200+ entries of the class type above in any random order. Such as:

{ id: 324234, date: 120519 }
{ id: 354633, date: 120519 }
{ id: 9999349, date: 130519 }

We want to create another list which groups the items by the data such as:

[
   120519: [
    { id: 324234, date: 120519 }
    { id: 354633, date: 120519 }
   ],
   130519: [
    { id: 9999349, date: 130519 }
   ],
]
StuartM
  • 6,743
  • 18
  • 84
  • 160
  • Demonstration of any potential attempt you have made so far? – Shahzad Hassan May 14 '19 at 00:17
  • Linq has a group expression. What specific problem have you encountered? https://stackoverflow.com/questions/7325278/group-by-in-linq. Sorry to be picky but fyi - properties should have capitalized names – JKerny May 14 '19 at 01:45

1 Answers1

0

use GroupBy

var groupedList = list.GroupBy(x=> x.date);

x=> x.date is yor selector that returns a value. you can use an expression as selector:

var groupedList = list.GroupBy(x=> x.date > someDate);

this will result two list one for dates after someDate and one for dates before it

GroupBy returns IEnumerable<IGrouping<SelectorType, DataType>>

also you can return an anonymous type as list's items. see GroupBy

Ali Abdollahi
  • 143
  • 11