I want to insert random elements into a existing database. Before I insert those random elements I have to check if they already exist in the database (primary key). I don't want to add an extra ID attribute.
Therefore I want to get the duplicates but only the duplicate primary keys, therefore .Union() does not work.
Here are two solutions:
var databaseList = database.Repository.GetAllElements();
foreach (var element in listOfRandomElements.Where(element => databaseList.Find(
x =>
x.Property0 == element.Property0 &&
x.Property1 == element.Property1 &&
x.Property2 == element.Property2)
!= null))
{
listOfElements.Remove(element);
}
listOfElements.RemoveAll(x => x.Property0 == databaseList.Select(y => true).Property0);
The first solution does not work, because I want to delete elements during the enumeration. I can fix this problem with a workaround (Intelligent way of removing items from a List<T> while enumerating in C#) but for me the whole expression looks horrible.
The second solution (last line of code) does not exist, but something like that would be great.
I hope you have better solutions, I would like to work with LINQ. Perfomance is secundary.
I thought about merging both lists and group them by the primary key, but then I have to delete the elements which have been in the databaseList, but how do I know which elements were in the databaseList.
As always there are hundreds ways of solving this problem, at leat I found one (first solution with a workaround), but maybe there's a more elegant way.