C# - 将多个 LINQ 查询合并为一个?
我使用了两个 LINQ 查询来操作数据表并返回我想要的数据。实际上,该表具有以下列:
Group Animal Numbers
一个组内可以有多个动物,并且可以为单个动物分配多个编号。最初我想计算每个特定动物的数字范围,然后计算每个组的平均范围。输出是组数,然后是平均范围。
我有以下两个 LINQ 查询,它们确实有效,但我的问题是,是否可以将其合并到单个查询中,或者,由于它们是不同的操作,是否应该将它们分开以提高可读性和可测试性?
//Calculate range/delta for each number per animal
var query = from data in Data.AsEnumerable()
group data by new { animal = data.Field<string>("animal"), gp = data.Field<string>("group") }
into g
orderby g.Key.gp
select new
{
animal = g.Key.animal,
gp = g.Key.gp,
delta = g.Max(c => Convert.ToDouble(c.Field<string>("numbers")))
- g.Min(c => Convert.ToDouble(c.Field<string>("numbers")))
};
//calculate average range/delta per group
var temp = from q in query
group q by q.gp
into g
select new
{
gp = g.Key,
average = g.Average(c => c.delta)
};
谢谢。
I have used two LINQ queries to manipulate a datatable and return the data that I want. Effectively, the table has the following columns:
Group Animal Numbers
There can be multiple Animals within a single group, and multiple numbers assigned to a single animal. Initially I want to calculate the range of the numbers for each specific animal, and then calculate an average range for each group. With the output being the group number and then the average range.
I have the following two LINQ queries, that do work, however my question is, can this be merged into a single query, or , as they are distinct operations, should they be kept seperate for readability and testability?
//Calculate range/delta for each number per animal
var query = from data in Data.AsEnumerable()
group data by new { animal = data.Field<string>("animal"), gp = data.Field<string>("group") }
into g
orderby g.Key.gp
select new
{
animal = g.Key.animal,
gp = g.Key.gp,
delta = g.Max(c => Convert.ToDouble(c.Field<string>("numbers")))
- g.Min(c => Convert.ToDouble(c.Field<string>("numbers")))
};
//calculate average range/delta per group
var temp = from q in query
group q by q.gp
into g
select new
{
gp = g.Key,
average = g.Average(c => c.delta)
};
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您没有强制第一个查询使用
ToArray()
之类的方法进行计算,因此组合这些查询没有任何优势。为了便于阅读,我会将它们分开。Because you aren't forcing the first query to evaluate with a method like
ToArray()
, there's no advantage to combining these queries. I would leave them separate for readability.您可以首先按
group
对数据进行分组,然后在嵌套查询中按animal
来计算增量的平均值:You could first group the data by
group
and then, in a nested query, byanimal
to calculate the average of the deltas: