我这里有这组数据。事件的属性EventGroups
类型为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;
我觉得最后一个块可以比它更干净地重写。我该怎么做才能让这个更干净?
答案 0 :(得分:4)
您可以使用Enumerable.ToList Extension Method转换IEnumerable&lt; T&gt;到一个新列表&lt; T&gt;:
foreach (var ev in e)
{
ev.EventGroups = g.Where(groups => ev.EventID == groups.EventID)
.ToList();
}
答案 1 :(得分:1)
您可以使用ToList()
折叠内部循环。
foreach ( var ev in e ) {
ev.EventGroups = g.Where( Groups => ( ev.EventID == Groups.EventID ) ).ToList();
}
外部循环已经是LINQy,因为它是一个副作用循环而且不是LINQy。
答案 2 :(得分:1)
这个例如
ev.EventGroups = g.Where( Groups => ( ev.EventID == Groups.EventID )).ToList();
想到了。