Reputation: 780
I have a list like below with more column. First two column is for entity A and second two column is for entity B. As you can see there is one to many relationship between these entities. So, I want to group this list to custom model.
QID ORDERNUMBER OPID POINT
1888 1 6902 4
1888 1 6903 3
1888 1 6904 2
1888 1 6905 1
1889 2 6906 4
1889 2 6907 3
1889 2 6908 2
1889 2 6909 1
1890 3 6910 4
1890 3 6911 3
1890 3 6912 2
1890 3 6913 1
First two column for Question object and other two column is for Options object list. This is my model
public class MyModel
{
public Question Question { get; set; }
public List<Option> Options { get; set; }
}
I need to group above table by QID. After that I need to take group key to Question object and assign QID's groups to list of Option object.
Simple demonstrade for one instance of MyModel should be;
MyModel > Question > QID:1888
ORDERNUMBER:1
> Options > [0] : OPID:6902
POINT:4
[1] : OPID:6903
POINT:3
[2] : OPID:6904
POINT:2
[3] : OPID:6905
POINT:1
Upvotes: 0
Views: 103
Reputation: 7204
Firstly, GroupBy
QID, ORDERNUMBER
, then, for each group, init the question and his questions
var models = list.GroupBy(q => new { q.QID, q.ORDERNUMBER})
.Select(g => new Model()
{
Question = new Question() { QID = g.Key.QID, ORDERNUMBER =g.Key.ORDERNUMBER} ,
Options = new List<Option>(g.ToList().Select(i => new Option() { OPID = i.OPID, POINT = i.POINT }))
})
Upvotes: 3