IQueryable,将匿名类型转换为强类型

时间:2010-09-30 22:43:09

标签: linq c#-4.0 anonymous-types

是否有更优雅/简洁的方式;我想用WorkListItem初始化代码摆脱foreach循环。

        var queryable = registrations.Select(
            r => new
                     {
                         r.Id, r.AccountNumber, r.DateAdded, r.DateUpdated, r.Patient, r.Patient.InsuranceInfos
                     });
        var list = queryable.ToList();

        var workListItems = new List<WorkListItem>();
        foreach (var anonymous in list)
        {
            var w = new WorkListItem
                        {
                            Id = anonymous.Id,
                            ClientAccountId = anonymous.AccountNumber,
                            DateAdded = anonymous.DateAdded,
                            DateUpdated = anonymous.DateUpdated,
                            Patient = anonymous.Patient,
                            InsuraceInfos = anonymous.Patient.InsuranceInfos
                        };
            workListItems.Add(w);
        }
        return workListItems;

1 个答案:

答案 0 :(得分:4)

是的,您可以完全删除“中间人”,并直接选择新的WorkListItem,如下所示:

var list = registrations.Select(r => new WorkListItem
           {
               Id = r.Id,
               ClientAccountId = r.AccountNumber,
               DateAdded = r.DateAdded,
               DateUpdated = r.DateUpdated,
               Patient = r.Patient,
               InsuraceInfos = r.Patient.InsuranceInfos
           }).ToList();