Say I have a list of objects like so
list <type>
---------------
o1: date-23.03
o2: date-23.03
o3: date-24.05
o4: date-25.05
How to make another list that contains inner lists of objects that has 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 an algorithm would be nice too.
Don't use a List<object> but a List<RealClass>
Presuming that it's actually a known type and that it's a DateTime property:
List<List<ClassName>> objectsbyDate = listOfObjects
.GroupBy(x => x.DateTimeProperty.Date)
.Select(g => g.ToList())
.ToList();
If it's actually string property as commented, why is that so? You should fix that. However, if you insist on a 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 string at the very last step if you want to display it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With