简体   繁体   中英

LINQ group by into a new list

I have two classes

public class groupedDoc { 
   public string gr_id = "";
   public string id = "";
   public string name = "";
   public subrec subRec = new subrec();
}

public class subrec {
   public List<record> record = new List<record>();
   '''
}

I want to group a List<record> allrecord based on the id and name into the object called groupedDoc .

This is what I do

var groupedList = allrecord.ToList().GroupBy(x => new { x.id ,x.name})
.Select(grp => new groupedRec
{
     gr_id = Guid.NewGuid().ToString(),
     id = grp.FirstOrDefault().id,
     name = grp.FirstOrDefault().name
})
.ToList();

But I also want to return the grouped record into the subrec.record . I tried subRec.record = grp.ToList() but get "invalid initializer member declarator". So anyone can help me to achieved that?

You have to also initialize subrec in the statement:

var groupedList = allrecord.ToList().GroupBy(x => new { x.id ,x.name})
.Select(grp => new groupedRec
{
     gr_id = Guid.NewGuid().ToString(),
     id = grp.Key.id,
     name = grp.Key.name,
     subRec = new subrec()
     {
         record = grp.ToList()
     }
})
.ToList();

I've replaced your id = and name = assignments with what I believe you were going for, to save creating more enumerators for the grouped records. As an aside, you should rename record to records as it represents more than one record.

I'd also recommend following Microsoft's naming conventions so that your code is easier for other people to follow, etc.

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