I have a generic list, which I use linq to search like so:
NotificationWindowItem item = itemList.Where(elm => elm.UID == UID).SingleOrDefault();
itemList.Where(elm => elm.UID == UID).SingleOrDefault().Read = true;
I then go on to call a WCF web service with values from item.
I do this since it is my understanding that SingleOrDefault() returns a new IEnumerable, with copies of the objects. (Did I misunderstand?)
The list is usually not very long, so the extra iteration is not very significant, but it really bugs me.
I just can’t think of a way to consolidate the two iterations.
Any ideas?
SingleOrDefaultdoes not return an IEnumerable but a single item instead. Since you already assign and keep it in your variableitem, why not simply use that for further processing?You can further simplify this. And, as pointed out by Tim, you need a null check (see below why):
To expand on your questions/unclarities:
List<NotificationWindowItem>which implementsIEnumerable<NotificationWindowItem>.IEnumerable<NotificationWindowItem>and creates anotherIEnumerable<NotificationWindowItem>that only contains matching elements.IEnumerable<NotificationWindowItem>and returns a normal, simple, single NotificationWindowItem. (More than that, it verifies that there only is a single matching element. If more than one element match it would throw an exception. If no element matches, it returnsdefault(T)which isnullin your case).itemis not anIEnumerable. It is aNotificationWindowItem. There is no magic behind. It is a simple object. It does not have anyhting to do with LINQ. You only used LINQ to retrieve it, but afterwards you can do anything you could do with any other instance of NotificationWindowItem.