5

在对匿名选择的 linq 查询中,我想连接来自两个属性的字符串。

例如,在某些人群中查找最年长的人的全名。

var personsAndOldest = db.Persons.GroupBy(person => person.SomeThingThatCanBeGroupedForPerson).Select(a => new
            {
                FirstName = a.FirstOrDefault().FirstName,
                LastName = a.FirstOrDefault().LastName,
                BirthDate = a.FirstOrDefault().BirthDate,
                FullnameOfOldes = a.Aggregate((pers1, pers2) => pers1.BirthDate > pers2.BirthDate ? pers1 : pers2).FirstName + " " //How do I get LastName of the old one (without using the full aggregate again)
            });

我是否必须再次编写完整的聚合才能在名字和空格之后获取 LastName?

4

3 回答 3

1

你可以这样做

var personsAndOldest = db.Persons
    .GroupBy(person => person.SomeThingThatCanBeGroupedForPerson)
    .Select(g => new 
        {
            a = g.First(),
            o = g.Aggregate((pers1, pers2) =>
                pers1.BirthDate > pers2.BirthDate ? pers1 : pers2)
        })
    .Select(pair => new
        {
            FirstName = pair.a.FirstName,
            LastName = pair.a.LastName,
            BirthDate = pair.a.BirthDate,
            FullnameOfOldes = pair.o.FirstName + " " + pair.o.LastName
        });
于 2012-11-15T15:30:50.817 回答
1

您可以在 Select 中使用 lambda 语句:

var personsAndOldest = db.Persons.GroupBy(person => person.SomeThingThatCanBeGroupedForPerson).Select(a => 
    {
        var first = a.First();
        var oldest = a.Aggregate((pers1, pers2) => pers1.BirthDate > pers2.BirthDate ? pers1 : pers2);
        return new
        {
            FirstName = first.FirstName,
            LastName = first.LastName,
            BirthDate = first.BirthDate,
            FullnameOfOldes = oldest.FirstName + " " + oldest.LastName)
        };
    });
于 2012-11-15T15:37:13.810 回答
0
  • 您可以使用let来引入新的范围变量。
  • 如果匿名类型等于分配属性的名称,则不需要指定属性名称
  • 我认为OrderBy会找到最年长的人(但您可以使用汇总并比较性能)
  • 我相信最年长的人是出生日期最少的人,因此您需要将聚合更改为pers1.BirthDate < pers2.BirthDate ? pers1 : pers2

所以

var personsAndOldest = from p in db.Persons
                       group p by p.SomeThingThatCanBeGroupedForPerson into g
                       let first = g.FirtOrDefault()
                       let oldest = g.OrderBy(x => x.BirthDate).FirstOrefault()
                       select
                       {
                           first.FirstName,
                           first.LastName,
                           first.BirthDate,
                           FullnameOfOldes = oldest.FirstName + " " + oldest.LastName
                       };
于 2012-11-15T15:45:28.460 回答