.NET对象映射,对对象进行分组

时间:2012-03-07 06:35:10

标签: .net automapper valueinjecter

假设我有一个像这样的对象列表:

public class FlatModel
{
    public string groupName { get; set; }
    public decimal value1 { get; set; }
    public decimal value2 { get; set; }
    public decimal value3 { get; set; }
}

我希望通过基于GroupName

的分组将它们映射到以下对象
public class GroupedModel
{
    public string groupName { get; set; }
    public List<ModelValues> values { get; set; }
}

public class ModelValues
{
    public decimal value1 { get; set; }
    public decimal value2 { get; set; }
    public decimal value3 { get; set; }
}

使用Automapper,Value Injector或其他一些对象映射实用程序是否有直接的方法?

1 个答案:

答案 0 :(得分:1)

它可以为你工作吗?

        var arr = new List<FlatModel>();

        var result = from p in arr
                     group p by p.groupName into g
                     select 
                         new GroupedModel { 
                             groupName = g.Key, 
                             values = (from q in g 
                                                select 
                                                    new ModelValues { 
                                                        value1 = q.value1, 
                                                        value2 = q.value2, 
                                                        value3 = q.value3 }).ToList() 
                         };