I'm doing a query which gets back the names of the buyers grouped by the brand of the products they have bought. So far I'm here
var query= from p in purchaseRepo.ReadAll()
join g in guitarRepo.ReadAll() on p.GuitarId equals g.Id
join b in brandRepo.ReadAll() on g.BrandId equals b.Id
group p by b.Id into grp
select new
{
grp.Key,
grp.SelectMany(t => t.BuyerName)
}
My problem is that I would like to have a List or an array of the buyer names declared in the select new part's body, but I can't get it to work. EDIT: I've given names for the fields is select new it looks like this:
select new
{
Brand=grp.Key,
Buyers=new List<string>()
};
Now I only need to know how to get the buyer names into the List. The result should be something like this: Brand1 --->List of buyer names
CodePudding user response:
Pick one:
- Linq offers the .ToList() method
- Linq offers the .ToArray() method
- Be a hero and implement your own method that accepts an IEnumerable<string> and returns a list populated with the string elements from that enumerable...
CodePudding user response:
I've managed to get it working, thanks everyone for the help!
Here's my query for others struggling:
var asd = from p in purchaseRepo.ReadAll()
join g in guitarRepo.ReadAll() on p.GuitarId equals g.Id
join b in brandRepo.ReadAll() on g.BrandId equals b.Id
group p by b.Name into grp
select new
{
Brand = grp.Key,
Buyers = grp.Select(t=>t.BuyerName)
};
var result = asd
.Select(x => new KeyValuePair<string, List<string>>(
x.Brand,
x.Buyers.ToList()
));