1

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.

2
  • foreach: no, you'll always have to iterate through the first collection at least once. All of these answers do that exactly once. What are you hoping to avoid? Commented Jan 27, 2011 at 14:46
  • The only way you can avoid it is a hack, where you modify the elements inside one of the LINQ query lambdas. The good style is to treat collection as immutable and modify the result w/o LINQ. Commented Jan 27, 2011 at 14:55

4 Answers 4

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

This works:

var valid = firstCollection.Where(f=> secondCollection.Any(s=> s.ID == f.ID));
foreach (var v in valid) { v.IsValid = true; }

Comments

0

This SO answer has more information about updating multiple rows using linq.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.