I have 2 collections and i have the following code to loop through one collection and see if it exists in another collection. If it does exist, then update a property of that item.
foreach (var favorite in myFavoriteBooks)
{
var book = allBooks.Where(r => r.Name == favorite.Name).FirstOrDefault();
if (book != null)
{
book.IsFavorite = true;
}
}
Is there a more elegant or faster way to achieve this code above?
You can use
Joinfor this, either in extension method syntax or LINQ syntax:Extension method:
LINQ:
These solutions are functionally identical; they differ only by syntax and they are faster than your original solution, since LINQ will build a hashtable on both sides and use that for matching rather than scanning the other list for every item in the original list.