Reputation: 850
How do I convert this code to a Lambda expression when there are two columns to select at the same time?
LINQ
var lq=(from a in tbl
group a by 0 into b
select new { intYear = b.Min(p => p.intYear), tintMonth = b.Max(p => p.tintMonth) }
).SingleOrDefault();
T-SQL
SELECT MIN(intYear), MAX(tintMonth)
FROM tbl
Lambda Expression
tbl.Select(x => x.intYear).Min(); //Can't figure how to select if 2 columns
Upvotes: 4
Views: 9454
Reputation: 116498
If you're intent on returning a "row" rather than two values, you can group all the rows together as you do in the first LINQ expression:
tbl.GroupBy(t => 1)
.Select(g => new { intYear = g.Min(p => p.intYear), tintMonth = g.Max(p => p.tintMonth) })
Note, I assume this is for LINQ-to-SQL. For plain old objects, this would most likely result in three iterations through the collection. One to do the grouping, one for the Min()
, and one for Max()
. For large collections, you would be be better off looping once and doing it the good-ol'-fashioned way with a single foreach
over the collection.
Upvotes: 6