将多个实体属性与实体列表进行比较

时间:2010-04-09 07:37:28

标签: c# linq

考虑这段代码:

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;
}

有更有效的方法吗?优选没有过于冗长; 从x中选择z ......如果可能的话。

1 个答案:

答案 0 :(得分:2)

您可以在班级(成分)上实现IComparable接口。这样你至少可以将比较代码嵌入到类中,而不需要额外的方法 这是一个链接:
http://www.c-sharpcorner.com/UploadFile/prasadh/IComparablePSD12062005010125AM/IComparablePSD.aspx