0

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. enter image description here

How do I go about this please?

0

2 Answers 2

2

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();
1
  • 2
    Like the answer, short and sweet. However, I would be interested to see Linq run times for handling distinct vs handling them yourself without merging and keeping track and what was found.
    – Matthew
    Commented Sep 6, 2022 at 3:58
1

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:

Try it online

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.