2

我这里有这组数据。事件有一个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;

我觉得最后一个块可以比现在更干净地重写。我该怎么做才能使这个更清洁?

4

3 回答 3

4

您可以使用Enumerable.ToList 扩展方法将 IEnumerable<T> 转换为新的 List<T>:

foreach (var ev in e)
{
    ev.EventGroups = g.Where(groups => ev.EventID == groups.EventID)
                      .ToList();
}
于 2011-06-22T03:33:20.853 回答
1

您可以使用 折叠内部循环ToList()

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

外部循环已经是 LINQy,因为它是一个副作用循环,而那些不是 LINQy。

于 2011-06-22T03:33:33.443 回答
1

例如这个

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

想到了。

于 2011-06-22T03:34:05.560 回答