Reputation: 494
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?
Upvotes: 0
Views: 845
Reputation: 38727
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.
Upvotes: 1