LINQ Group by string and count grouped property's child property

半世苍凉 提交于 2019-12-11 05:06:36

问题


I have written a code like below:

 Session["priceRange"] = ranges.Select(r => new PriceRangeGraph
                {
                    Price = Math.Round(r, 2),
                    Sales = lista.Where(x => ranges.FirstOrDefault(y => y >= x.SalePrice) == r).Sum(x => x.SaleNumber),
                    SuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() > 0).Count(),
                    UnSuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() == 0).Count(),
                }).ToList();

These are the two problematic lines of code:

SuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() > 0).Count(),
UnSuccessfulSellers = lista.GroupBy(x => x.StoreName).Where(x => ranges.FirstOrDefault(y => y >= x.Select(z => z.SalePrice).FirstOrDefault()) == r && x.Select(h => h.SaleNumber).FirstOrDefault() == 0).Count(),

In sales property as you can see I'm finding the price range where the item was sold and then I simply sum all sales within the given range.

Now I'm trying to see how many successful/unsuccessful users (with their usernames) have made sales within that given ranges.

So for example user test123 made 5 sales, test1234 made 4 sales, test56 made 0 sales in range 0-20$

The output for this range would be:

SuccessfulSellers=2
UnSuccessfulSellers = 1

The code above that I tried doesn't gives me correct results at all...

As you can see I'm grouping by the user's username to get the occurance number, and then filter the range for which user had made the sale, and then simply add another and statement to filter out those with =0 sales and those with more than 0 sales...

What am I doing wrong here?


回答1:


I think your issue is one of order of ops. Once you group by, you're actually dealing with a much more complex data structure: a list of lists, basically. Save your group by until after your filter(s), and your life will be much easier.

For example:

allSales.Where(m => m.Price >= 0 && m.Price <= 20)
     .GroupBy(m => m.User)
     .Select(m => new { User = m.Key, Sales = m.Count() });


来源:https://stackoverflow.com/questions/42629365/linq-group-by-string-and-count-grouped-propertys-child-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!