Re: Update one item in a BindingList



EitanB,

You should cycle through the items using the indexer, and not foreach,
like so:

for (int index = 0; index < myList.Count; ++index)
{
// Get the item.
MyStruct myStruct = myList[index];

// Modify the item here.

// Assign the item back.
myList[index] = myStruct;
}

The reassignment is necessary as you are working with what I assume is a
value type, so accessing properties off instances of that type returned by
the indexer would not change the value in the list.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx


"Eitan" <Eitan@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:42F74FED-F7A0-45FB-B171-797343D56D4C@xxxxxxxxxxxxxxxx
Please look at the code and the following question...

public BindingList<MyStruct> myList ;

foreach ( Object item in myList )
{
MyStruct myStruct = (MyStruct)item;
myStruct .Name = "any new name" ;

///
/// Question: I need to update myList with the updated myStruct, how is
the
most
/// efficient way to replace/update the old item in the
list
}

Thanks
EitanB



.



Relevant Pages

  • Re: Are collections ordered and other questions
    ... > While there's no rule requiring it that I'm aware of, ... > IEnumerable just returns an IEnumerator. ... > differed each time through a foreach, ... >> I think if a collection has an indexer, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Are collections ordered and other questions
    ... indexer property. ... While there's no rule requiring it that I'm aware of, foreach will usually ... IEnumerable just returns an IEnumerator. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: "cost" of generic dictionaries ?
    ... I also forgot to say that "foreach" better expresses intent; ... linked list that provided an int indexer. ... I would expect "foreach" to simply ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: speed about foreach , copy list to an arry then loop
    ... Ryan Liu wrote: ... iterator, which in some cases will be faster than an indexer, and in ...
    (microsoft.public.dotnet.languages.csharp)