开发者

Update using Linq Query

I 开发者_Go百科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.


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;
}


This works:

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜