开发者

Comparing multiple entity properties against list of entities

开发者 https://www.devze.com 2022-12-25 23:56 出处:网络
Consider this snippet of code: var iList = new List<Entities.Ingredient> { new Entities.Ingredient { Name = \"tomato\", Amount = 2.0 },

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号