Search code examples
.netautomappervalueinjecter

.NET Object mapping, grouping objects


Lets say that I have a list of objects like so:

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

and I want to map them to the following object, by grouping based on 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; }
}

Is there a straight-forward way to do this using Automapper, Value Injector, or some other object mapping utility?


Solution

  • Can it work for you?

            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() 
                             };