How to group then select items into a new class in LINQ (C # preferred)
Hi I'm trying to figure out the grouping and then create my own class as a result. I know that the result of the group is an IGrouping collection, but can I access the rows as they are instantiated to add a couple of flags with a custom class to them?
I have a FlightTimes class with some data, but I would like to add some data to the rows, like FlagRedEye. So I created a FlightTimeResult class with the original FlightTime class data plus a flag.
Can I do it? I can't figure out how to get it to work. I like to use strong types until I understand what's going on. I had to change a few things to protect my client, so I apologize for any syntax errors.
IGrouping<string, FlightTimeResult> FlightTimes =
( from flighttimes in schedules.FlightTimes
group flighttimes by flighttimes.FlightType.ToString()
into groupedFlights
select new FlightTimeResult( )
{
FlightTimeData = FlightTime, // Original class data
FlagRedEye = (FlightTime.departureTime.Hour >= 0 &&
FlightTime.departureTime.Hour < 6) // Extra flag
} )
The goal is to have a FlightTimesResult set (optional FlightTime + flag) grouped by FlightType. Not sure how to access individual FlightTime lines in the "select new FlightTimeResult ()" query
Do I need to use subquery in groupedFlights?
Many thanks.
source to share
This is most easily obtained by explicitly calling the Linq functions like this:
IQueryable<IGrouping<string, FlightTimeResult>> query
= schedules.FlightTimes.GroupBy(
ft => ft.FlightType.ToString(), // key
ft => new FlightTimeResult() { // your constructed objects for key
FlightTimeData = ft,
FlagRedEye = (ft.departureTime.Hour >= 0 && ft.departureTime.Hour < 6)
}
);
The two argument operation takes two lambda arguments as arguments - one to retrieve the keys, and one to retrieve the values for it.GroupBy
Also keep in mind that a group by operation (whether building group itm by key
or calling GroupBy
) returns a collection IGrouping<,>
- none.
So it will be IEnumerable<IGrouping<,>>
or IQueryable<IGrouping<,>>
.
source to share
I think you are on the right track. Instead of grouping FlightTimes by FlightType, try creating FlightTimeResults and grouping them using FlightType:
var results =
from ft in schedules.FlightTimes
group new FlightTimeResult
{
FlightTimeData = ft,
FlagRedeye = ft.DepartureTime.Hour >= 0 && ft.DepartureTime.Hour < 6
}
by ft.FlightType.ToString()
into groupedFlights
select groupedFlights;
source to share