Reputation: 4964
I have a list of objects like this:
public class Entity
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
| Id | Date |
| 1 | 2017-01-16 12:58:32 |
| 2 | 2017-01-16 11:36:01 |
| 3 | 2017-01-16 17:55:19 |
| 4 | 2017-01-19 13:19:40 |
| 5 | 2017-01-19 09:21:55 |
And I would like to filter this using LINQ to count the number of ocurrences by day. So the result would be something like this:
| Date | Occurrences |
| 2017-01-16 | 3 |
| 2017-01-17 | 2 |
Is it possible to do this with LINQ?
Upvotes: 0
Views: 897
Reputation: 111
Here are two Solutions:
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqExample
{
class Program
{
public class Entity
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
static void Main(string[] args)
{
List<Entity> entities = new List<Entity>()
{
new Entity() { Id = 1, Date = DateTime.Parse("2017-04-14 21:02:37")},
new Entity() { Id = 2, Date = DateTime.Parse("2017-04-14 21:03:42")},
};
var OccurencesPerDay = from entity in entities
group entity by entity.Date.Date into g
select new {Date = g.Key.Date, Occurences = g.Count()};
// Above is more readable than, even though both are equal
OccurencesPerDay = entities.
GroupBy(ent => ent.Date.Date).
Select(ents => new { Date = ents.Key.Date, Occurences = ents.Count()} );
Console.WriteLine($"| Date | Occurences |");
foreach (var occ in OccurencesPerDay)
{
Console.WriteLine($"| {occ.Date} | {occ.Occurences} |");
}
}
}
}
Upvotes: 1
Reputation: 34421
Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication49
{
class Program
{
static void Main(string[] args)
{
List<Entity> entities = new List<Entity>() {
new Entity() { Id = 1, Date = DateTime.Parse("2017-01-16 12:58:32")},
new Entity() { Id = 2, Date = DateTime.Parse("2017-01-16 11:36:01")},
new Entity() { Id = 3, Date = DateTime.Parse("2017-01-16 17:55:19")},
new Entity() { Id = 4, Date = DateTime.Parse("2017-01-19 13:19:40")},
new Entity() { Id = 5, Date = DateTime.Parse("2017-01-19 09:21:55")}
};
var results = entities.GroupBy(x => x.Date.Date).Select(x => new { count = x.Count(), entities = x.ToList() }).ToList();
}
}
public class Entity
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
}
Upvotes: 1
Reputation: 62213
You want to use GroupBy
var lst = new List<Entity>(); // populate with your data
var result = lst
.GroupBy(x => x.Date.Date, x => x.Id)
.Select(x => new { Date = x.Key, Occurrences = x.Count() });
Upvotes: 5