2

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?

bmt22033
  • 6,880
  • 14
  • 69
  • 98

2 Answers2

2

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 1
    If this is a reference type, you can make this work - as he's modifying values within the class, and not trying to add or remove from the collection. – Reed Copsey Jan 25 '13 at 18:04
  • @ReedCopsey - For the sake of making me sound right, you're only using LINQ to get the objects, not setting the value so you're really not using LINQ for everything in the question. Heh. – Justin Niessner Jan 25 '13 at 18:06
  • True - You'd only be using LINQ for part of it :) – Reed Copsey Jan 25 '13 at 18:07
2

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373