c#按名称和日期列出<object>组计算List <dictionary <string,string>&gt;

时间:2015-07-06 01:08:08

标签: c# linq

如果我有课:

public class Custom
{
   public Custom()
   {

   }

   public DateTime TargetDate { get; set; }
   public string Name { get; set; }
   public decimal Price { get; set; }
   public decimal Value { get; set; }
}


List<Custom> customItems = new List<Custom>();

上面的列表可以包含任意数量的可以相同或不同地调用的项目。这些项目可以在任何一天,甚至在一个特定日期称为相同的多个项目。

如何使用linq按名称和日期对列表进行分组,并为属性价格计算sum,为属性值计算average

基本上,结果应该是List&gt;以及为每个分组名称+日期计算的属性。

这是我到目前为止所尝试的。

var aggdata = customItems.GroupBy(t => new { t.Name, t.TargetDate.Date })
              .ToDictionary(t => t.Key.Name, t => t.Sum(x => x.Price));

但是我错过了字典中的平均值和日期值。

结果应该是这样的:

"TargetDate", "01.01.2015"
"Name", "SomeName"
"Value", "123"   // Average of values
"Price", "1234"  // Sum of price values

.........

2 个答案:

答案 0 :(得分:2)

您可以使用所需的所有属性投影到匿名对象。如果您在多个日期拥有该名称,那么该词典投影将会出现问题。您可能希望改为投射到Lookup。这允许您拥有多个键。

var aggdata = customItems.GroupBy(t => new { t.Name, t.TargetDate.Date })
          .ToLookup(t => t.Key.Name, t => new {
              Date = t.Key.Date,
              Average = t.Average(x => x.Value),
              Sum = t.Sum(x => x.Price)
          });

答案 1 :(得分:1)

这对我有用:

var query =
    from ci in customItems
    group ci by new { ci.TargetDate, ci.Name } into gcis
    select new Custom()
    {
        TargetDate = gcis.Key.TargetDate,
        Name = gcis.Key.Name,
        Price = gcis.Sum(x => x.Price),
        Value = gcis.Average(x => x.Value),
    };

List<Custom> results = query.ToList();

使用此示例数据:

List<Custom> customItems = new List<Custom>()
{
    new Custom() { TargetDate = DateTime.Now.Date, Name = "Foo", Price = 1m, Value = 2m, },
    new Custom() { TargetDate = DateTime.Now.Date, Name = "Foo", Price = 2m, Value = 4m, },
    new Custom() { TargetDate = DateTime.Now.Date, Name = "Bar", Price = 3m, Value = 8m, },
};

我得到了这些结果:

results

相关问题