Reputation: 34407
I have two collections. One have an ID(int) and IsIDValid(bool) variable. and Other collection has ID(int). I want to update first collection's IsIDValid property to true, if the ID exist in second collection.
EDIT: Thanks for the answers. Can I somehow do it without using foreach loop.
Upvotes: 1
Views: 782
Reputation: 34408
Along the lines of Jon's, you could also use LINQ's Join
var query = firstCollection.Join(other, fc => fc.Id, o => o.Id, (fc, o) => fc);
foreach (var item in query)
{
item.IsIdValid = true;
}
which is essentially the same thing except you're letting LINQ chose the strategy for merging the two sets rather than explicitly building a HashSet yourself. I've no idea which is more efficient under the covers but I'd hope Join was at least as good.
Upvotes: 0
Reputation: 18877
This SO answer has more information about updating multiple rows using linq.
Upvotes: 0
Reputation: 39600
This works:
var valid = firstCollection.Where(f=> secondCollection.Any(s=> s.ID == f.ID));
foreach (var v in valid) { v.IsValid = true; }
Upvotes: 0
Reputation: 1499770
Simple:
var validIds = new HashSet<int>(other.Select(x => x.Id));
var query = firstCollection.Where(x => validIds.Contains(x.Id));
foreach (var item in query)
{
item.IsIdValid = true;
}
Upvotes: 1