如何只添加新的城市

本文关键字:城市 添加 | 更新日期: 2023-09-27 18:27:42

我有CreateDiscountViewByUser discountViewByUser,它包含用户选择的城市列表,但它们可能已经是已添加的城市。

List<DiscountCity> discountCities = (from city in db.DiscountCities
                                 where city.DiscountId == discountViewByUser.Id
                                 select city).ToList();
            for (int y = 0; y < discountCities.Count(); y++)
            {
                var dc = discountCities[y];
                bool flag = false;
                for (int i = 0; i < discountViewByUser.DiscountCitys.Length; i++)
                {    
                    if (dc.CityId == discountViewByUser.DiscountCitys[i])
                    {
                        flag = true;
                        discountCities.Remove(dc);
                        y--;
                    }                      
                }
                if (!flag)
                {
                    db.DiscountCities.DeleteObject(dc);    
                }
            }
            foreach (var dc in discountCities)
            {
                DiscountCity discountCity = new DiscountCity
                                                {Id = Guid.NewGuid(),
                                                 CityId = dc.CityId,
                                                 DiscountId = main.Id};
                db.DiscountCities.AddObject(discountCity);
            }

如何只增加新的城市?我的代码不起作用=(

更新:

discountViewByUser.DiscountCitys type int[].
db.DiscountCities table: Id DiscountId CityId.

示例:数据库中:敖德萨,基辅

用户集:敖德萨,莫斯科。

我需要删除基辅和莫斯科怎么做?

如何只添加新的城市

我建议添加所有项目,然后删除重复项。

// Where uniqueList is a List<T> of unique items:
uniqueList.AddRange(valuesToAdd);
uniqueList = uniqueList.Distinct(new CityEqualityComparer()).ToList();
// Sorry, I don't know how this would fit into your code

由于您正在按城市ID比较城市,因此可能需要使用自定义IEqualityComparer来确定哪些城市是重复的。

下面是这样一个类的例子:

class CityEqualityComparer : IEqualityComparer<City>
{
    public bool Equals(City arg1, City arg2)
    {
        return arg1.CityId == arg2.CityId;
    }
    public int GetHashCode(City arg)
    {
        return arg.CityId;
    }
}

这个问题可能也会有所帮助。

我建议您分两步完成。

1) 查找要删除的城市

var deleteCities = db.DiscountCities.Where(c => c.DiscountId == discountViewByUser.Id
        && !discountViewByUser.DiscountCitys.Contains(c.CityId));
foreach(deleteCity in deleteCities)
{
   db.DiscountCities.DeleteObject(deleteCity);
}

2) 查找要插入的城市ID

var insertCities = discountViewByUser.DiscountCitys.Except(
           db.DiscountCities.Where(c => c.DiscountId == discountViewByUser.Id)
                            .Select(c => c.CityId));
foreach(var insertCity in insertCities)
{
    DiscountCity discountCity = new DiscountCity
           {Id = Guid.NewGuid(), CityId = insertCity, DiscountId = discountViewByUser.Id};
    db.DiscountCities.AddObject(discountCity);    
}