简体   繁体   中英

Grouping List elements and map to new model using Linq

I have list of items that should be converted to another data structure using Linq statements. I am able to group list, however, I cannot correctly create subelements.

Here is my result model (simplified):

public class MyModel {
    string Name {get; set;}
    List<MySubmodel> Submodels {get;set;}
}

public class MySubmodel {
    string Id {get;set;}
    string Title {get;set;}
    ...
}

Here is source:

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 list elements of class SourceModel partly match MySubmodel and I have a mapper that maps src list elements to 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>() 
                        };

You need to simply project the IGrouping<string,MyModel> object recieved after grouping. Try this:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM