tags:

views:

52

answers:

1

Consider this snippet of code:

var iList = new List<Entities.Ingredient>
{
    new Entities.Ingredient { Name = "tomato", Amount = 2.0 },
    new Entities.Ingredient { Name = "cheese", Amount = 100.0 }
};


var matches = new DataContext().Ingredients.Where(i => Comparer(i, iList));


private Boolean Comparer(Entities.Ingredient i, List<Entities.Ingredient> iList)
{
    foreach (var c in iList)
    {
        if (c.Name == iList.Name && c.Amount >= iList.Amount) return true;
    }

    return false;
}

Is there a more efficient way of doing this? Preferably without being too verbose; from x in y select z... If thats at all possible.

+2  A: 

You could implement the IComparable interface on your class (Ingredient). That way you will at least keep the comparison code embedded in the class itself with no need for the extra method.
Here is a link:
http://www.c-sharpcorner.com/UploadFile/prasadh/IComparablePSD12062005010125AM/IComparablePSD.aspx

Henrik Söderlund
But then I'd have to re-implement that interface each time I would change my dbml-file (drag 'n drop LINQ to SQL).
roosteronacid
... Or just implement the interface in a partial class. Great! :)
roosteronacid
Yes, that works. The alternative would be to use an external IEqualityComparer<T>, but the "partial class with interface" solution is more elegant.
Henrik Söderlund
In case you are interested in the IEqualityComparer<T>: http://msdn.microsoft.com/en-us/library/ms132151.aspx
Henrik Söderlund