Search code examples
c#linqdictionarycomparisonicomparable

Comparing two custom objects


public class Filter
{
    public int A { get; set; }
    public int B { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

What is the best way, to compare two Filter objects according with sometimes one, and sometimes all properties? I mean I have Dictionary<Filter, string> and I need find all KeyValuePairs compatibile with used filter, e.g:

var f1 = new Filter(){A = 1}
var f2 = new Filter(){A = 1, Start = DateTime.Now, End = DateTime.AddHour(2)}

var dict = new Dictionary<...>()
dict.Add(new Filter(){A = 1}, "asdf");
dict.Add(new Filter(){A = 1}, Start = DateTime.Now.AddHours(-1), "qwerty");

Now usigng f1 I'd like find both KeyValuePairs, but using f2 I'd like to find only first KVP, because of Start in second object doesn't fulfill condition Start + End from f2 (it is outside the scope)

EDIT Dictionary is outside of the scope of this question. It has to be. I need only mechanism of the comparing. I don't create dictionary to do it. I need it to store some data important for me.


Solution

  • How about something like this:

        IEnumerable<KeyValuePair<Filter, string>> DoIt(Dictionary<Filter, string> dict, Filter f)
        {
            return dict.Where
                (d => 
                    (f.A == null || d.Key.A == f.A) && 
                    (f.B == null || d.Key.B == f.B) && 
                    (f.Start == null || f.Start < d.Key.Start) /* && Condition for End */);
        }
    

    I think the condition is not exactly what you wanted, but you'll probably be able to figure it out from here...