>>>>Hi All, is it possible in a "Linq type way" to set properties of class instances which are in a IList ? , for example I have a list of names and addresses in a list and if there are some that share a certain residential area code (e.g. UK ) I would like to set a property in the instances, hope this makes sense.
>>>
>>>Closest you can get is probably something like:
foreach(Info i in list.Where(x=>x.Postcode.StartsWith="HR"))
>>> {
>>> i.SomeProperty = true;
>>> }
>>
>>List does have a foreach method (
http://msdn.microsoft.com/en-us/library/bwabdf9z%28v=vs.110%29.aspx), but its not really recommended (
http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). There is also a parallel foreach (
http://msdn.microsoft.com/en-us/library/dd992001%28v=vs.110%29.aspx) you could use if setting the value has no side effects.
>
>Not sure I agree with the arguments against .ForEach. Anyway, interesting that Reflector for ForEach shows::
public void ForEach(Action<T> action)
>{
> if (action == null)
> {
> ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
> }
> for (int i = 0; i < this._size; i++)
> {
> action(this._items[i]);
> }
>}
and foreach:
public bool MoveNext()
>{
> if (this.version != this.list._version)
> {
> ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
> }
> if (this.index < this.list._size)
> {
> this.current = this.list._items[this.index];
> this.index++;
> return true;
> }
> this.index = this.list._size + 1;
> this.current = default(T);
> return false;
>}
fwiw
(1) Think for( ; ; )is quicker than for each
(2) Your reflector code of the ForEach shows it is using a for( ; ; )
Gregory