kei*_*itn 2 .net c# 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
};
}
Run Code Online (Sandbox Code Playgroud)
我希望能够使用它来调用它
ExecQuery(c => c.Sum(a=>a.Price));
ExecQuery(c => c.Count());
Run Code Online (Sandbox Code Playgroud)
我觉得我很亲密.
你太亲密的朋友,试试以下它应该为你解决问题:
public class testtable
{
public DateTime TransactionDate { get; set; }
public float? Price { get; set; }
}
public List<testtable> tests = new List<testtable>();
Run Code Online (Sandbox Code Playgroud)
您的方法现在应该如下所示:
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
};
}
Run Code Online (Sandbox Code Playgroud)
为了测试我们的代码:
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());
}
Run Code Online (Sandbox Code Playgroud)
然后该方法的结果应该是:
为总和: { Month = 1, Total = 30.0 } and { Month = 3, Total = 70.0 }
为了计数: { Month = 1, Total = 2.0 } and { Month = 3, Total = 2.0 }
另外一条评论请decimal用于价格,它更常见,更好的金融数量.
希望这可以帮助 :)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |