Reputation: 10147
How can the following be achieved with only 1 Linq query? Is it more efficient?
var o = new myObject {
Value =
(from value in g
select value.Value).FirstOrDefault(),
Id =
(from value in g
select value.Id).FirstOrDefault(),
... }
Upvotes: 1
Views: 366
Reputation: 223422
var result = (from value in g
select new
{
Value = value.Value,
ID = value.ID
}).FirstOrDefault();
EDIT: (Based on Edited question)
In that case I would rather have the value first and then use that in the constructor for my object. Your select may involve a condition or where clause. I think in Linq to object, performance is not going to matter that much, or may be it depends on the collection size, but I still believe it will be minimal. Still the best approach would be to select the item first and then use it in object initialization.
var result = (from value in g
select new
{
Value = value.Value,
ID = value.ID
}).FirstOrDefault();
var o = new myObject{Value = result.Value, ID = result.ID}
Upvotes: 2