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.

+3


source to share


2 answers


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.

+7


source


Grouping by your date object:



List<object> list = new List<object> {o1,o2,o3,o4};

var result = list.GroupBy(g => g);
foreach(var group in result) {
    Console.WriteLine(group.Key);
}

      

+1


source







All Articles