Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top