我有使用Linq语句转换为另一个数据结构的项目列表。我能够对列表进行分组,但是,我无法正确创建子元素。
这是我的结果模型(简化):
public class MyModel {
string Name {get; set;}
List<MySubmodel> Submodels {get;set;}
}
public class MySubmodel {
string Id {get;set;}
string Title {get;set;}
...
}
这是来源:
public class SourceModel
string Id {get;set;}
string Title {get;set;}
...
string Name {get;set;} // this is property for grouping
}
public List<SourceModel> src = getList();
src
列的SourceModel
个元素的元素与MySubmodel
部分匹配,我有一个将src
列表元素映射到MySubmodel
的映射器。)
IEnumerable<MyModel> t = from p in src
group p by p.Name into sl
select new MyModel()
{
Name = sl.Key,
// and I am not able to create MoelSublists object
ModelSublists = new List<MySubmodels>()
};
答案 0 :(得分:4)
您需要简单地投影分组后收到的IGrouping<string,MyModel>
对象。试试这个: -
IEnumerable<MyModel> t = from p in src
group p by p.Name into sl
select new MyModel()
{
Name = sl.Key,
ModelSublists = sl.Select(x => new MySubmodel
{
Id = x.Id,
Title = x.Id
}).ToList()
};