How do I rewrite this to be more LINQy?

假如想象 提交于 2019-12-11 01:46:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!