【发布时间】:2013-04-20 18:19:22
【问题描述】:
CHV1 CDD1 CHV2 CDD2 CHV3 CDD3 CHV4 CDD4 SortCol SearchColCount
---- -------------------------------------------------- ---- -------------------------------------------------- ---- -------------------------------------------------- ----------- ------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------ --------------
Adventure Cafe Columbus Back Of The House Cook 624 Adams, Donald, 4180259, A A, Adams, Donald, 4180259 0
Adventure Cafe Columbus Back Of The House Cook 643 Conard, Virgil, 4180469, A A, Conard, Virgil, 4180469 0
Adventure Cafe Columbus Back Of The House Cook 629 Pheiffer, Seth, 4180373, A A, Pheiffer, Seth, 4180373 0
Adventure Cafe Columbus Back Of The House Cook 645 Sees, Patrick, 4180474, A A, Sees, Patrick, 4180474 0
Adventure Cafe Columbus Back Of The House Cook 657 Walter, Derek, 4180508, A A, Walter, Derek, 4180508 0
以上是数据库中的数据集。
我正在尝试使用 LINQ 获取数据集并根据上述数据结构创建自定义对象类型,但该对象的成员之一是 List 数据类型。
我最初找到了以下文章,但它并不完全有效,因为它是一个简单的字符串 List 对象类型: Convert Datatable to Object with Linq and Group by 这给了我以下错误:
不能隐式转换类型 'System.Collections.Generic.IEnumerable' 到“System.Collections.Generic.List”。 存在显式转换(您是否缺少演员表?)
我已经列出了我对上述参考文章中代码的改编。理想情况下,我希望能够根据 CDD2、CDD3、CDD4 等动态创建多个“folderItem”列表……CDD 列的数量是可变的,这会使事情变得更加复杂。
此数据最终将以 JSON 形式从 WCF 服务返回。
dnFolders = from row in dnDataTable.AsEnumerable()
group row by new
{
id = row.Field<string>(1),
value = row.Field<string>(2)
} into folder
select new folder
{
id = folder.Key.id,
value = folder.Key.value
folderItem = section.Select(r=>r.Field<String>(3)).ToList()
};
文件夹类定义:
public class folder
{
[DataMember(Name = "id", Order = 1)]
public string id { get; set; }
[DataMember(Name = "value", Order = 2)]
public string value { get; set; }
[DataMember(Name = "type", Order = 3)]
public string type { get; set; }
[DataMember(Name = "sortCol", Order = 4)]
public string sortCol { get; set; }
[DataMember(Name = "folderItems", Order = 5)]
public List<folderItem> folderItems { get; set; }
}
folderItem 类定义
public class folderItem
{
[DataMember(Name = "value", Order = 1)]
public string value { get; set; }
[DataMember(Name = "id", Order = 2)]
public string id { get; set; }
[DataMember(Name = "type", Order = 2)]
public string type { get; set; }
}
【问题讨论】: