Search matched list in dictionary

754 views Asked by At
public class Filter
{
    public List<int> A { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}
var f1 = new Filter(){A = new List<int>() {1}}
var f2 = new Filter(){A = new List<int>() {1 , 4, 2}, Start = DateTime.Now, End = DateTime.AddHour(2)}

var dict = new Dictionary<Filter, string>()
dict.Add(new Filter(){A = new List<int>() {1}}, "asdf");
dict.Add(new Filter(){A = new List<int>() {4}}, "qwerty");
dict.Add(new Filter(){A = new List<int>() {3}}, "qwertyasd");

I need to get:

with f1 item first

with f2 items first and second.

How to construct linq query?

When A is int, It's simple

dict.Where(k =>
k.Key.A.Equals(filter.A)
&& k.Key.Start.CompareTo(filter.Start) > 0 
&& k.Key.End.CompareTo(filter.End) < 0
)

but when it ist List<int> it's more complicated for me.

3

There are 3 answers

4
Tigran On BEST ANSWER

Just use Contains and invert the control

dict.Where(k =>
    filter.A.Contains(k.Key.A[0]) //CONTAINS !
    && k.Key.Start.CompareTo(filter.Start) > 0 
    && k.Key.Start.CompareTo(filter.End) < 0
)
1
M. Mennan Kara On

You can use Intersect method

dict.Where(k =>
            k.Key.A.Intersect(filter.A).Any()
            && k.Key.Start.CompareTo(filter.Start) > 0
            && k.Key.End.CompareTo(filter.End) < 0
        );

Edit: Added Intersect since there are two lists involved.

0
Raphaël Althaus On

If at least one element of Filter.A must match one element of dict.Key.A, you can also do.

Cause I don't see the interest of having a List... for just one int !

var result = dict.Where(k =>
                           filter.A.Intersect(k.Key.A).Any());