Getting Only The Top Row From Each Group
I have some code that groups a table by "Valu开发者_如何学Pythone1" and some loops that add the top row of each group to a list. This is a pretty ugly way to do this, and I was wondering if I could replace one of the foreach loops with a couple more lines in my LINQ query? Problem is, I don't have the foggiest idea how to do this.
var Result =
from a in DB.Table1
group new {Values = a} by a.Value1 into c
select new {everything = c};
foreach (var Row in Result)
{
foreach (var RowAll in Row.Everything)
{
List.Add(new List<string>() {RowAll.Value1, RowAll.Value2})
break;
}
}
Use Enumerable.First:
var List =
(from Row in Result
let RowAll = row.Everything.First()
select new List<string>() {RowAll.Value1, RowAll.Value2}
).ToList();
Or, combined with your original query:
var List =
(from a in DB.Table1
group a by a.Value1 into c
select new List<string>() {c.Key, c.First().Value2}
).ToList();
Use FirstOrDefault:
var query = from row in result
let rowAll = row.Everything.FirstOrDefault()
where rowAll != null
select new List<string> {rowAll.Value1, rowAll.Value2};
var list = query.ToList();
Rereading you first query I realised you are grouping on a property of 'a' so there should be no empty groupings. First() should be safe as in the other posters example.
精彩评论