Reputation: 2548
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
Upvotes: 0
Views: 1859
Reputation: 48975
You could use either .SingleOrDefault()
or .Single()
.
var product = (from p in productList
where p.Id == "xyz"
select new Product()
{
Id = p.Id,
-,
-
}).Single();
If productList
is already a list of Product
, then don't rebuild a new instance of the Product
object using select new
.
You could simply do:
var product = productList.SingleOrDefault(p => p.Id == ...);
Upvotes: 0
Reputation: 9027
You can use the more sensible "method"-syntax instead of the query syntax.
var product = productList.SingleOrDefault(p => p.Id == "xyz");
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 Id xyz
, 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.
Upvotes: 3
Reputation: 11989
List<Product> productList = GetList();
var product = (from p in productList
where p.Id == "xyz"
select new Product()
{
Id = p.Id,
-,
-
}).SingleOrDefault();
Upvotes: 0