简体   繁体   中英

How to group and select multiple object in linq c#

PersonList = PersonList
           .GroupBy(s => s.LastName)
           .Select(g => new Person { 
                LastName = g.Key,
                Period = g.Select(p => p.Period), 
                Time = string.Join("  ", g.Select(v => CheckTime(v.Time, v.Period) + "' " + v.Gtype)) })
           .ToList();

I have this linq statement and I am getting this error:

Cannot implicitly convert type System.Collection.Generic.Ienumerable<string> to 'string' .

Is it possible to select multiple properties of the object of person

Modify like this

Your code:

Period = g.Select(p => p.Period)

Modified code:

Period = g.Select(p => p.Period).FirstOrDefault()

Assuming you want unique groups for lastname and period (and not something like the first period in the name group), you can group on both LastName and Period with .GroupBy(s => new{s.LastName, s.Period}) . The key will contain both properties:

PersonList = PersonList
       .GroupBy(s => new {s.LastName, s.Period})
       .Select(g => new Person { 
            LastName = g.Key.LastName,
            Period = g.Key.Period,
            Time = string.Join("  ", g.Select(v => CheckTime(v.Time, v.Period) + "' " + v.Gtype)) })
       .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM