Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Lambda get two properties as string from aggretation

Inside a linq query to an anonymous select I want to concatenate strings from two properties.

For instance to find the full name of the oldest person in some grouping of persons.

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)
            });

Do I have to write the full aggregation again to get the LastName after the firstname and whitespace?

like image 991
Leiv Halvor Lauvsnes Avatar asked Nov 04 '22 11:11

Leiv Halvor Lauvsnes


2 Answers

You could use a lambda statement in the Select:

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)
        };
    });
like image 61
Eren Ersönmez Avatar answered Nov 09 '22 13:11

Eren Ersönmez


You can do this as

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
        });
like image 42
Rawling Avatar answered Nov 09 '22 12:11

Rawling