I have a IList<Customer>
and I want to find a customer whose la开发者_如何转开发stname='smith'. how do i do that? The .where looks like it might work but I don't understand the predicate needed to do this. Or is there a better way to search the list?
Thanks, rod.
Try this, assuming that your IList is the customers
object:
var smiths = customers.Where(c => c.LastName == "Smith");
To expand on the other posts:
Any method such as Where()
that takes a predicate needs that predicate to return a boolean. That predicate will be evaluated against each element of the collection, and for each element where the predicate returns true
, that element will be included in the resulting collection.
Keep in mind that Where()
returns a collection (I believe IEnumerable<Customer>
in your scenario, but I don't have VS open right now to verify) that you will need to get an individual element from using First()
or Single()
(among others). You can also use the predicate on any of the single methods such as Single()
or Last()
to avoid chaining Where(x => blah).Single()
.
If you want the first customer which his last name is 'smith', use FirstOrDefault
var customer = customerList.FirstOrDefault(c => c.LastName == "smith");
if (customer != null)
// do code;
And If you want all the customers which their last name is 'smith', use Where
:
var customers = customerList.Where(c => c.LastName == "smith");
foreach(var customer in customers)
// do code;
Good luck!
精彩评论