tags:

views:

53

answers:

2

Hi,

I have the following situation. I have a list of items which have an "Id". I have to search for an item with a specific id, modify its values and maintain the order of the collection. What would be the best way to do that?

var collection = <some_linq_query>

collection.Where(i=>i.Id=someId).FirstOrDefault().Property = "bla";

// now collection should be the same but the item updated.
+1  A: 

As long as the objects in the collection are mutable, your code should work fine.

By the way, FirstOrDefault takes an optional filter parameter, so you can write collection.FirstOrDefault(i => i.Id == someId).

SLaks
I don't think it is, if I add var item = collection.Where(i=>i.Id=someId).FirstOrDefault(); and hover over it with the debugger, the attribute is the old value.
Javaa
Does your collection contain `struct`s?
SLaks
no structs, thanks for the filter tip!
Javaa
+2  A: 

The call to Where does not modify the original LINQ query stored in collection in any way. Instead it creates a new IEnumerable<T> where is a subset of the original query. The subset will have the same relative ordering as the original set in collection

The only way this could cause a problem is if the value collection is a LINQ where which has a Where clause, or is otherwise filtered, base on the value of Property. If that is the case and you want to preserve the order force collection into a non-lazy evaluated structure via .ToList.

collection = collection.ToList();
JaredPar
Thanks this helped! Extra points if you can post me an example of using the property for the ToDictionary(..) method :D
Javaa