-1

我要向集合中添加一个对象,但我想知道如何更新它,如果记录存在并且不存在记录。

我要为此努力。

public void AssignProductSetting(CategoryType catType, int catId, int freeCount)
        {
            this.CustomSettings.Add(new ProductCustomization()
            {
                CategoryID = catId,
                CustomizationType = catType,
                DefaultFreeCount = freeCount,
                ProductID = this.ProductID
            });
        }
4

2 回答 2

2
if(CustomeSettings == null) CustomerSettings = 
                                    new Collection<ProductCustomization>();

var cat = CustomSettings.FirstOrDefault(r=>r.CategoryId == catID && 
                                           r.CustomizationType == catType);
if(cat!=null)
{ 
     cat.DefaultFreeCount = freeCount;
     cat.ProductID = this.ProductID;
}
else
{
     this.CustomSettings.Add(new ProductCustomization()
        {
            CategoryID = catId,
            CustomizationType = catType,
            DefaultFreeCount = freeCount,
            ProductID = this.ProductID
        });
 }
于 2013-08-02T12:49:59.327 回答
1
if(this.CustomSettings.Any(x=>x.CategoryID == catId))
{
  //Update
} 
else
{
  //Add
}
于 2013-08-02T12:48:43.790 回答