I want to get object in a list. I have following code
List<Product> productList = GetList();
var product = (from p in productList
where p.Id == "xyz"
select new Product()
{
Id = p.Id,
-,
-
});
foreach ( var p in product)
{
//some code
}
I need to get object directly into var product
You can use the more sensible “method”-syntax instead of the query syntax.
Edit: There’s a couple of different methods you can use to get the element you’re after.
.SingleOrDefault()will try to find the item you’re looking for, returning null (default) if there is no object matching your expression..Single()will do the same thing, except it will throw an exception if the object wasn’t found..FirstOrDefault()will get a list of objects matching your expression, and retrieve the first one. If there’s several objects with Idxyz, both.Single()and.SingleOrDefault()will throw an exception..First()works like.FirstOrDefault()but similarly to.Single()will throw an exception if you didn’t find what you were looking for.