I have two arrays of dates. I want to merge them into one array that stores each (distinct) dates and their occurrences in their parent arrays.
For example:
var today = new DateTime (year:2022, month:01, day:01);
var firstDateArray = new DateTime[] { today.AddDays(1), today.AddDays(7), today, today.AddDays(3), today };
var secondDateArray = new DateTime[] { today.AddDays(7), today, today.AddDays(3), today.AddDays(3), today.AddDays(1) };
I want to get something like this as a result.
How do I go about this please?
CodePudding user response:
Here I used a tuple (DateTime, int, int)
to represent the data:
List<(DateTime, int, int)> result = firstDateArray.
Concat(secondDateArray).
Distinct().
Select(x => (
x,
firstDateArray.Where(y => y == x).Count(),
secondDateArray.Where(z => z == x).Count()
)).
ToList();
CodePudding user response:
You can use .GroupBy
, .Select
, and .Join
for this:
var today = new DateTime (year:2022, month:01, day:01);
var firstDateArray = new DateTime[] { today.AddDays(1), today.AddDays(7), today, today.AddDays(3), today };
var secondDateArray = new DateTime[] { today.AddDays(7), today, today.AddDays(3), today.AddDays(3), today.AddDays(1) };
var firstGrouped = firstDateArray
.GroupBy(d => d)
.Select(g => new { Date = g.Key, Count = g.Count() });
var secondGrouped = secondDateArray
.GroupBy(d => d)
.Select(g => new { Date = g.Key, Count = g.Count() });
var joined = firstGrouped
.Join(secondGrouped, f => f.Date, s => s.Date, (f, s) => new { Date = f.Date, FirstCount = f.Count, SecondCount = s.Count })
.OrderBy(j => j.Date)
.ToList();
GroupBy
basically collects items with a common key (in this case the DateTime
) and then lets you iterate through the collections.
Join
takes 4 arguments: the second enumerable, the key selector for the first, the key selector for the second (it uses these to facilitate the join), and the result selector to produce the result you want.
Documentation: