Reputation: 209
I have two lists.
Client List : one of them receive from user (client)
Server List : one of them get from database .
I want to do 3 work on this lists .
One : Add ( if data not exists in server List and exist in the client List )
Two : Remove data ( if exist in the server List and not exist in the client List )
Three : Update ( if data exist in server List and client Server and data has Changed )
This is my model:
public class CategoryPropertyDto
{
public Guid? Id { get; set; }
public Guid CategoryId { get; set; }
public string PropName { get; set; }
public CategoryPropertyType CategoryPropertyType { get; set; }
}
the client send me the list of this model CategoryPropertyDto
.
Now I write this code for adding data:
var currentValue = getAllPropByCategory.Result.Select(x => new CategoryPropertyDto
{
CategoryId = x.CategoryId,
CategoryPropertyType = x.CategoryPropertyType.CategoryPropertyType,
Id = x.Id,
PropName = x.PropName
}).ToList();
/// Add New Property
var newProp = request.CategoryPropertyDtos.Where(x => x.Id == null).ToList();
List<CategoryProperty> CategoryProperty = new List<CategoryProperty>();
if (newProp.Count() > 0)
{
foreach (var item in newProp)
{
CategoryProperty.Add(new CategoryProperty(item.PropName, item.CategoryPropertyType, item.CategoryId));
}
await unitOfWork.CategoryRepository.CategoryPropertyRepository.AddBulkCategoryProperty(CategoryProperty, cancellationToken);
}
and its worked well.
Now I want to find items for remove (exist in the server List but not exist in the clientList)
var removeValue = currentValue.Except(request.CategoryPropertyDtos).ToList();
but it did not work and return all currentValue
and I don't know how can I find the items for update.
How can I solve this problem?
Upvotes: 0
Views: 1621
Reputation: 4461
var removeValue = currentValue.Except(request.CategoryPropertyDtos).ToList();
This line does not work because in this case Except method compare References, not Values and obviously currentValue items have different references than client items.
solution: You have to use Id in all cases (add, delete, update) as you already did for Add case. So for example to find items to delete:
var ItemIdsToDelete = currentValue.Select(p => p.Id).Except(request.CategoryPropertyDtos.Select(p => p.Id)).ToList();
and delete items by id using method like this:
await unitOfWork.CategoryRepository.CategoryPropertyRepository.DeleteBulkCategoryPropertyById(ItemIdsToDelete, cancellationToken);
and you can do similar thing to find items that their ids exist in both client and server lists and update them.
Upvotes: 1