How do I rewrite this to be more LINQy?

c# dapper linq

Question

I have this set of data here. Events has a property EventGroups that is of type List<Groups>

List<Events> e;
List<Groups> g;

// Get the data from the database using dapper
using( var con = DataAccessMaster.GetOpenConnection( ) ) {
    using( var multi = con.QueryMultiple( sprocname, new { StartDate = fromDate, EndDate = toDate }, commandType:CommandType.StoredProcedure ) ) {
        e = multi.Read<Events>( ).ToList( );
        g = multi.Read<Groups>().ToList();
    }
}

// Only put the groups that belong to one another within the related event so that when we goto bind it will be painless
foreach ( var ev in e ) {
    ev.EventGroups = new List<Groups>();
    foreach ( Groups group in g.Where( Groups => ( ev.EventID == Groups.EventID ) ) ) {
        ev.EventGroups.Add( group );
    }
}

return e;

I feel like the last block could be rewritten more cleanly than it is. What can I do to make this cleaner?

Accepted Answer

You can use the Enumerable.ToList Extension Method to turn an IEnumerable<T> into a new List<T>:

foreach (var ev in e)
{
    ev.EventGroups = g.Where(groups => ev.EventID == groups.EventID)
                      .ToList();
}

Popular Answer

This for instance

ev.EventGroups = g.Where( Groups => ( ev.EventID == Groups.EventID )).ToList();

comes to mind.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why