public class A
{
public double K {get; set;}
and other fields in here
}
I have a Dictionary of List<A>
indexed by Datetime
,
Dictionary<System.Datetime, List<A>>;
How do I get the intersection of all the List<A>
, returned again as a Dictionary<System.Datetime, List<A>>
? Intersection meaning the largest List<A>
that such that each Datetime
contains that A.K
.
I can do it with for loops. But I am looking for a performant elegant solution in Linq
.
{'5-19-2015', List<20, 25, 27, 30>
'6-10-2015', List<20, 25, 27, 28>
'9-5-2015', List<20, 21, 22, 23, 24, 25, 26,27,28,29,30}
Would return
{'5-19-2015', List<20, 25, 27>
'6-10-2015', List<20, 25, 27>
'9-5-2015', List<20, 25, 27>}
EDIT 1
As per the suggestion below, I tried this but it doesn't work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestLinq
{
public class A : IComparable, IEquatable<A>
{
public double K { get; set; }
public int CompareTo(object obj)
{
A other = (A)obj;
if (this.K > other.K)
return 1;
if (this.K < other.K)
return -1;
return 0;
}
public bool Equals(A other)
{
return this.K == other.K;
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<DateTime, List<A>> dict = new Dictionary<DateTime, List<A>> {
{ DateTime.Now, new List<A> {
new A { K = 20 }, new A { K = 25 }, new A { K = 27 }, new A { K= 30 } } },
{ DateTime.Now.AddDays(1), new List<A> {
new A { K = 20 }, new A { K = 25 }, new A { K = 27 }, new A { K = 28 } } },
{ DateTime.Now.AddDays(2), new List<A> {
new A { K = 20 }, new A { K = 21 }, new A { K = 22 }, new A { K = 23 }, new A { K = 24 },
new A { K= 25 }, new A {K= 26 }, new A { K=27 }, new A {K= 28 }, new A { K=29 }, new A { K =30 } }
}};
var intersectedList = dict.Values.Skip(1)
.Aggregate(
new HashSet<A>(dict.Values.First()),
(h, e) => { h.IntersectWith(e); return h; }
);
Console.ReadLine();
}
}
}