如何在LINQ中使用分组?

时间:2015-02-20 12:58:41

标签: c# linq windows-phone-8 windows-phone

我只想澄清我的问题。这是我的数据库

Title      Amount       Tags
Food       5            Hotel,Friends
Food       6            Hotel
Family     8            Hotel,Mobile
Family     9            Electricity
Food       8            Party

我希望生成如下报告:

期望输出:

Percentage     Title             Amount
53%            Food              19
                  Hotel             11
                  Friends           5
                  Party             8

57%            Family            17
                 Hotel             8
                 Mobile            8
                 Electricity       9

我对LINQ没有足够的了解。所以我在这个发现中遇到了很多麻烦。

我现在使用的代码,

var ReportingData = ReportListQuery.Where(Item => Item.Category == "expense")
                                   .GroupBy(x => new { x.Title, x.TagsReport })
                                   .Select(y => new
                                         {
                                             Percentage = Math.Round((y.Sum(x => x.Amount) / MonthExpense) * 100),
                                             ExpenseTitle = y.First().Title,
                                             ExpenseCalculation = y.Sum(x => x.Amount)
                                          });

这是我代码的输出:

输出:

Percentage     Title      Amount  
53%            Food       19
57%            Family     17

提前致谢。请帮我。 : - (

1 个答案:

答案 0 :(得分:1)

据我了解你的问题,你不知道如何获得每个标签的结果,对吗?

首先,我强烈建议在复杂的LINQ查询中使用有意义的名称,而不是x,y等。在我看来,你按照TagsReport进行分组,我没有看到原因。最后,代替y.First()。标题,您可以使用组密钥。应用这些建议后,您的简化查询如下所示:

var ReportingData = ReportListQuery
    .Where(Item => Item.Category == "expense")
    .GroupBy(item => item.Title)
    .Select(itemGroup => new
    {
        Percentage = Math.Round((itemGroup.Sum(item => item.Amount) / MonthExpense) * 100),
        ExpenseTitle = itemGroup.Key,
        ExpenseCalculation = itemGroup.Sum(item => item.Amount)
    });

现在,要为每个标记添加结果,您可以在包含标记金额列表的匿名类型上生成另一个属性:

var ReportingData = ReportListQuery
    .Where(Item => Item.Category == "expense")
    .GroupBy(item => item.Title)
    .Select(itemGroup => new
    {
        Percentage = Math.Round((itemGroup.Sum(item => item.Amount) / MonthExpense) * 100),
        ExpenseTitle = itemGroup.Key,
        ExpenseCalculation = itemGroup.Sum(item => item.Amount)
        TotalTagAmounts = itemGroup
            .SelectMany(item => item.Tags.Select(tag => new { Tag = tag, Amount = amount})
            .GroupBy(tagAmount => tagAmount.Tag)
            .Select(tagAmountGroup => new 
            { 
                Tag = tagAmountGroup.Key, 
                TotalAmount = tagAmountGroup.Sum(tagAmount => tagAmount.Amount)
            })
    });