将聚合传递给Linq查询

时间:2018-03-22 09:23:21

标签: c# .net linq lambda

除了聚合不同之外,我有几个几乎相同的查询。我正在尝试创建一个可以传递聚合函数的方法。到目前为止我的努力看起来像

public void ExecQuery(Func<IEnumerable<testtable>, float?> filter)
{           
    var results = from a in testtable
                  group a by a.TransactionDate.Month into j
                  select new
                  {
                      Month = j.Key,                              
                      Total = filter
                  };
}

然后我希望能够使用

来调用它
ExecQuery(c => c.Sum(a=>a.Price));      
ExecQuery(c => c.Count());

我认为我非常接近。

1 个答案:

答案 0 :(得分:5)

你太亲密的朋友,请尝试以下方法,它应该为你解决问题:

 public class testtable
 {
    public DateTime TransactionDate { get; set; }

    public float? Price { get; set; }
 }

 public List<testtable> tests = new List<testtable>();

您的方法现在应该如下:

public void ExecQuery(Func<IEnumerable<testtable>, float?> filter)
{
   var results = from a in tests
   group a by a.TransactionDate.Month into j
   select new
   {
      Month = j.Key,
      Total = filter(j)//actually this the little update needed here
   };
}

为了测试我们的代码:

    static void Main(string[] args)
    {
        tests.Add(new testtable() { Price = 10, TransactionDate =new DateTime(2018,1,1,0,0,0) });
        tests.Add(new testtable() { Price = 20, TransactionDate = new DateTime(2018, 1, 2, 0, 0, 0) });
        tests.Add(new testtable() { Price = 30, TransactionDate = new DateTime(2018, 3, 1, 0, 0, 0) });
        tests.Add(new testtable() { Price = 40, TransactionDate = new DateTime(2018, 3, 2, 0, 0, 0) });
        ExecQuery(c => c.Sum(a => a.Price));
        ExecQuery(c => c.Count());
    }

然后该方法的结果应为:

总和:{ Month = 1, Total = 30.0 } and { Month = 3, Total = 70.0 }

计数:{ Month = 1, Total = 2.0 } and { Month = 3, Total = 2.0 }

此处还有一条评论请使用decimal作为价格,这对于金融数量来说更为常见且更好。

希望这会有所帮助:)