user4972421
user4972421

Reputation:

How to find duplicate in a list and update the same list

In my model 'City' having the following properties

publi class City{
            public string CityCode { get; set; }
            public string CityName { get; set; }
            public string Remarks { get; set; }
}

While updating the entries,I check the duplicate only for CityName.If I want to update Remarks I can't do it.Here is my Linq query

public void Update(City model)
        {
            var dup = (from c in _CityRepository.TableNoTracking
                       where c.CityName.Equals(model.CityName)
                       select c.CityName).FirstOrDefault();
            if (dup == null)
            {
                City city = new City();
                city.CityCode=model.CityCode;
                city.CityName = model.CityName;
                city.Remarks = (model.Remarks==null)?string.Empty:model.Remarks;
                _CityRepository.Update(city);
             }
        }

If I want to check duplicate Cityname Except for that CityCode means How to do that?

Upvotes: 0

Views: 154

Answers (2)

user4972421
user4972421

Reputation:

Using this query I can find the existence of CityName

 var dup = (from c in _CityRepository.TableNoTracking
                           where c.CityName.Equals(model.CityName) && c.CityCode!=model.CityCode
                           select c.CityName).FirstOrDefault();

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

In your code dup is name of city. It's better to use Any operator to check if there exists city with same name:

bool exists = _CityRepository.TableNoTracking
                 .Any(c => c.CityName == model.CityName);

But it's not enough to only check if city exists. You need to get saved entity and update it with values from model. For searching city by name, you can use overloaded FirstOrDefault operator which accepts predicate:

var city = _CityRepository.TableNoTracking
              .FirstOrDefault(c => c.CityName == model.CityName);

Then check if city was found and update it with values from model (you don't need to update city name, because you searched by name):

if (city != null)
{
    city.CityCode = model.CityCode;
    city.Remarks = model.Remarks ?? string.Empty;
    _CityRepository.Update(city);
}
else
{
    // there is no match, so you need to create new city and save it
}

Also keep in mind that city name might be not unique. It's better to search by city code. And if you don't need to update code and name, you can just update remarks.

Upvotes: 2

Related Questions