0

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

-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;
}
4

1 回答 1

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);
        }

希望这可以帮助

于 2013-07-15T19:00:26.987 回答