Group array elements by date
Let's say I have a list of such objects
list <type>
---------------
o1: date-23.03
o2: date-23.03
o3: date-24.05
o4: date-25.05
How do I create another list containing internal lists of objects that have the same date? For example:
new list<list<type>>
-----------------------
List<type> innerList1 {o1, o2}
List<type> innerList2 {o3}
List<type> innerList3 {o4}
Possible LINQ solutions would be cool, but the algorithm would be nice too.
source to share
Don't use List<object>
butList<RealClass>
Assuming it is a really known type and that it is a property DateTime
:
List<List<ClassName>> objectsbyDate = listOfObjects
.GroupBy(x => x.DateTimeProperty.Date)
.Select(g => g.ToList())
.ToList();
If this is indeed a property string
as a comment, why is it? You must fix this. However, if you insist on string
, you can still use Enumerable.GroupBy
. But what if two objects have different years? You won't even mention it since the year is not stored.
Instead, convert a DateTime
to a string in the very last step if you want to display it.
source to share