Reputation: 31
I'm using Entity Framework 6.3 and LINQ to query from a table and populate the DTO object below:
public class MyObject
{
public string Name { get; set; }
public List<int> Number { get; set; }
public MyClass()
{
Number = new List<int>();
}
}
In this particular table (legacy project), the Name can have multiple Numbers, hence my need to use it as a list.
The table looks like this:
Name Number
abc 15371
abc 15079
abc 15371
abc 30392
xyz 30373
xyz 13141
My code, for now, is as follow:
List<MyObjetct> myObject = new List<MyObjetct>();
myObject = contex.TableName.Where(x => listOfNames.Contains(x.Name))
.Select( y => new MyObject()
{
name = y.name
number = *populate the list of numbers*
});
I was hoping to populate a list of MyObjects with names and a list o numbers.
Upvotes: 0
Views: 1637
Reputation: 7803
Try this:
myObject = contex.TableName.GroupBy(t => t.Name)
.Where(g => listOfNames.Contains(g.Key))
.Select(g => new MyObject()
{
name = g.Key,
number = g.Select(n => n.Number).ToList()
}).ToList();
Output:
Name / Numbers
abc / 15371,15079,15371,30392
xyz / 30373,13141
I noticed your data sample has repeat name/number combinations. Not sure if it's just a typo or if you need to account for that.
Upvotes: 4