问题
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?
回答1:
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();
}
回答2:
You can collapse the inner loop with ToList()
.
foreach ( var ev in e ) {
ev.EventGroups = g.Where( Groups => ( ev.EventID == Groups.EventID ) ).ToList();
}
The outer loop is already as LINQy as it can get, because it is a side-effecting loop and those are not LINQy.
回答3:
This for instance
ev.EventGroups = g.Where( Groups => ( ev.EventID == Groups.EventID )).ToList();
comes to mind.
来源:https://stackoverflow.com/questions/6434601/how-do-i-rewrite-this-to-be-more-linqy