Linq查询:按多列分组

时间:2013-07-15 18:39:01

标签: linq list c#-4.0 grouping

我有一个看起来像这样的列表。

-100 Smith, Jane $1000
-100 Smith, John $1100.00
-100 Smith, Cole $840.00
-110 Jones, Harry $1270.00
-110 Jones, Diane $870.00
-111 Jones, Richard $1560.00

使用LINQ,我希望编写一个查询,允许我按族汇总值。 第一个标识符是系列ID。 对于上面的记录集,我的输出将如下所示:

-100 Smith $2940.00
-110 Jones $2140.00
-111 Jones $1560.00

这是我的代码:

static void Main(string[] args)
{
    _fi = FillIncome();
    var query = (from f in _fi group f by f.familyId into delta select new {familyId = delta.Key, amount = delta.Sum(x => x.income) });
    foreach (var q in query)
    {
        Console.WriteLine(q);
    }}
static List<FamilyIncome> FillIncome()
{
    var income = new List<FamilyIncome>();
    var fi = new FamilyIncome {familyId = -100, lastname = "Smith", firstname = "Jane", income = 1000};
    income.Add(fi);
    fi = new FamilyIncome { familyId = -100, lastname = "Smith", firstname = "John", income = 1100 };
    income.Add(fi);
    fi = new FamilyIncome { familyId = -100, lastname = "Smith", firstname = "Cole", income = 840 };
    income.Add(fi);
    fi = new FamilyIncome { familyId = -110, lastname = "Jones", firstname = "Harry", income = 1270 };
    income.Add(fi);
    fi = new FamilyIncome { familyId = -110, lastname = "Jones", firstname = "Diane", income = 970 };
    income.Add(fi);
    fi = new FamilyIncome { familyId = -111, lastname = "Jones", firstname = "Richard", income = 1600 };
    income.Add(fi);

    return income;
}

1 个答案:

答案 0 :(得分:2)

我们假设代表您的数据项的类如下所示:

    class DataItem
    {
        public int FamilyId { get; set; }

        public string FamilyName { get; set; }

        public string FirstName { get; set; }

        public decimal Salary { get; set; }
    }

然后您的数据应显示为

    private static DataItem[] items = new[]
        {
            new DataItem { FamilyId = -100, FamilyName = "Smith", FirstName = "Jane", Salary = 1000},
            new DataItem { FamilyId = -100, FamilyName = "Smith", FirstName = "John", Salary = 1100},
            new DataItem { FamilyId = -100, FamilyName = "Smith", FirstName = "Cole", Salary = 840},
            new DataItem { FamilyId = -110, FamilyName = "Jones", FirstName = "Harry", Salary = 1270},
            new DataItem { FamilyId = -110, FamilyName = "Jones", FirstName = "Diane", Salary = 870},
            new DataItem {FamilyId = -111, FamilyName = "Jones", FirstName = "Richard", Salary = 1560}, 
        };

产生所需输出的查询如下:

        var groupedItems =
            from item in items
            group item by new {item.FamilyId, item.FamilyName}
            into family
            select new {family.Key.FamilyId, family.Key.FamilyName, Sum = family.Sum(item => item.Salary)};

要输出这些分组的项目,您可以使用类似

的内容
        foreach (var groupedItem in groupedItems)
        {
            Console.WriteLine(
                "{0}\t{1}\t{2}", 
                groupedItem.FamilyId, 
                groupedItem.FamilyName, 
                groupedItem.Sum);
        }

希望这有帮助