Question

Wood for the trees moment I'm sure.

var dateListA = new List<DateTime>();
var dateListB = new List<DateTime>();

for (var date = DateTime.Parse("01-Dec-2013"); date <= DateTime.Parse("08-Dec-2013"); date = date.AddDays(1))
    dateListA.Add(date);

for (var date = DateTime.Parse("05-Dec-2013"); date <= DateTime.Parse("10-Dec-2013"); date = date.AddDays(1))
    dateListB.Add(date);

var results = distinct_Merge_Of_dateListA_And_dateListB_But_With_New_WasInListB_Boolean_Property => new { Date, WasInListB };

foreach (var result in results)
{
    System.Console.WriteLine("{0} {1}", result.Date, result.WasInListB);
}

Expected output

01-Dec-2013 No
02-Dec-2013 No
03-Dec-2013 No
04-Dec-2013 No
05-Dec-2013 Yes
06-Dec-2013 Yes
07-Dec-2013 Yes
08-Dec-2013 Yes
09-Dec-2013 Yes
10-Dec-2013 Yes

I'm trying two merge to lists but indicate in the final list (with a boolean) if the result was included in list B. Any hints on how to do is are appreciated.

Was it helpful?

Solution

You can use:

var newInA = dateListA.Except(dateListB);
var results = newInA
                 .Select(d => new { Date = d, WasInListB = false })
                 .Concat(dateListB.Select(d => new { Date = d, WasInListB = true }));

This will give you the results you listed. It lists items that are only found in A first, then all items from B.

OTHER TIPS

Use a dictionary. Classic bin approach:

var results = new Dictionary<DateTime,bool>();
foreach( var date in dateListA )
 results[date] = false;
foreach( var date in dateListB )
 results[date] = true;
foreach (var result in results)
 System.Console.WriteLine("{0} {1}", result.Key, result.Value);

Hope this helps, Just tested and I believe this does just what you are looking for...although a more efficient method may be possible.

var dateData = dateListB.Select(x => new { Date = x, InB = true }).Union(dateListA.Except(dateListB).Select(x => new { Date = x, InB = false })).ToList();

Good Luck!

If you want to discard all dates from B that are also in A, you could achive this with a GroupBy, then selecting only the first element from each group (which will be from A if there are two, since A was added first

 dateListA.Select(a => new { Date = a, FromB = false })
         .Concat(dateListB.Select(b => new { Date = b, FromB = true })
         .GroupBy(x=>x.Date)
         .Select(gp=> gp.First());

If you want to know whether an item occured in A and in B, you could use

 dateListA.Select(a => new { Date = a, FromB = false })
         .Concat(dateListB.Select(b => new { Date = b, FromB = true })
         .GroupBy(x=>x.Date)
         .Select(gp=> new {Date = gp.Key, FromA = gp.Any(x=>!x.FromB), FromB = gp.Any(x=>x.FromB));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top