代码之家  ›  专栏  ›  技术社区  ›  cllpse

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

  •  1
  • cllpse  · 技术社区  · 16 年前

    请考虑下面这段代码:

    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到y选择z ... 如果可能的话。

    1 回复  |  直到 16 年前
        1
  •  2
  •   Henrik Söderlund    16 年前

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