views:

989

answers:

2

Hi There

I need to find a match of an item in a IQueryable list. I have a list as follows:

IQueryable<EventItem> eventItems = new Queryable<EventItem>();
EventItem eventItem1 = new EventItem("Event 1");
EventItem eventItem2 = new EventItem("Event 2");
eventItems.Add(eventItem1);
eventItems.Add(eventItem2);

I now want to find the event in the list by passing in an EventItem like eventItem2. How do I search and return item something like EventItem found = eventItems.Select(eventItem2);

Cheers,

S

+1  A: 

Linq proviedes a .Where method that lets you pass in a lambda expression to evaluate the item you're looking for.

EventItem found = eventItems.Where(e => e == eventItem2).SingleOrDefault();

found could be null, so you just need to check for that to see whether it was found in the queryable/list

Joel Martinez
You spelt SingleOrDefault wrong.
Daniel Earwicker
you just caught the answer before I fixed it ;-)
Joel Martinez
Thanks Joel, always simple when you see it
+4  A: 

using LINQ you can do:

EventItem found = eventItems.SingleOrDefault(item => item.Name == "Event 2");

Assuming that the name for the EventItem is exposed via a Name property.

The item => [code] part is where you provide a method that returns true/false, to decide whether the items match or not.

Nader Shirazie
Shame this wasn't accepted, it was first, more succint/readable, more efficient and spelt correctly on the first try!
Daniel Earwicker
Cheers! Tho as long as people see the answer, it's all good.
Nader Shirazie