Linq中默认值的平均扩展方法 [英] Average extension method in Linq for default value
问题描述
任何人都知道如何为平均值设置默认值吗?我有这样一条线...
Anyone know how I can set a default value for an average? I have a line like this...
dbPlugins = (from p in dbPlugins
select new { Plugin = p, AvgScore = p.DbVersions.Average(x => x.DbRatings.Average(y => y.Score)) })
.OrderByDescending(x => x.AvgScore)
.Select(x => x.Plugin).ToList();
如果我还没有评级,这会引发错误.如果没有,我希望平均值默认为0.我想这应该是一种扩展方法,在其中可以指定默认值.
which throws an error becase I have no ratings yet. If I have none I want the average to default to 0. I was thinking this should be an extension method where I could specify what the default value should be.
推荐答案
有: DefaultIfEmpty
.
我不确定您的DbVersions
和DbRatings
是什么,以及哪个集合正好有零个项目,但这是这样的想法:
I 'm not sure about what your DbVersions
and DbRatings
are and which collection exactly has zero items, but this is the idea:
var emptyCollection = new List<int>();
var average = emptyCollection.DefaultIfEmpty(0).Average();
更新 :(重复以下评论中的内容以提高知名度)
Update: (repeating what's said in the comments below to increase visibility)
如果发现自己需要在类类型的集合上使用DefaultIfEmpty
,请记住,您可以将LINQ查询更改为项目之前进行汇总.例如:
If you find yourself needing to use DefaultIfEmpty
on a collection of class type, remember that you can change the LINQ query to project before aggregating. For example:
class Item
{
public int Value { get; set; }
}
var list = new List<Item>();
var avg = list.Average(item => item.Value);
如果您不想/无法构造默认的Item
,且Value
等于0,则可以先投影到int
s的集合,然后然后提供一个默认值:
If you don't want to/can not construct a default Item
with Value
equal to 0, you can project to a collection of int
s first and then supply a default:
var avg = list.Select(item => item.Value).DefaultIfEmpty(0).Average();
这篇关于Linq中默认值的平均扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!