我该如何重写它以使其更LINQy

本文关键字:LINQy 重写 何重写 | 更新日期: 2023-09-27 18:00:02

这里有这组数据。事件具有类型为List<Groups> 的属性EventGroups

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;

我觉得最后一个块可以重写得更干净。我该怎么做才能让它更干净?

我该如何重写它以使其更LINQy

您可以使用Enumerable.ToList扩展方法将IEnumerable<T>进入新的列表<T>:

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

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

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

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

例如

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

脑海中浮现。