简体   繁体   中英

Select objects in binding list that match criteria using LINQ?

I have a BindingList that contains 100,000 objects. Each object contains a bool property that indicates whether the object has been modified or not. I basically want to loop through the objects and when I find one with that bool property set to true, I want to set it to false. Something similar to this:

foreach (myObject obj in bindingListOfMyObjects)
{
    if (obj.Modified)
    {
        obj.Modified = false;
    }
}

Is it possible to do this using LINQ? And would that be any faster than the code above?

No. There's no way of doing this in LINQ. For this to work, you need to modify the elements directly in the BindingList . LINQ would simply return a new IEnumerable .

You could use Enumerable.Where to filter the collections, and them modify them in your loop:

foreach (myObject obj in bindingListOfMyObjects.Where(o => o.Modified))
     obj.Modified = false;

This will not be any faster, though it may be slightly easier to understand the intent.

Note that you wouldn't, in general, use LINQ to actually make the modifications - LINQ queries, by their nature, should not cause side effect (changing the value). They are intended to be used as queries - so filtering the objects is appropriate, and then setting in a loop. For details, I recommend reading Eric Lippert's post on ForEach vs foreach .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM