首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从linq查询中获取平均值

问从linq查询中获取平均值
EN

Stack Overflow用户
提问于 2011-04-30 02:57:38
回答 1查看 447关注 0票数 0

我需要从下面的linq查询中获得平均值,但数据字段是varchar,这样做时我得到了错误。

代码语言:javascript
复制
var _districtResult = (from ls in SessionHandler.CurrentContext.LennoxSurveyResponses
                                   join ml in SessionHandler.CurrentContext.MailingListEntries on ls.SurveyCode equals ml.SurveyCode
                                   join m in SessionHandler.CurrentContext.MailingLists on ml.MailingListId equals m.MailingListId
                                   join ch in SessionHandler.CurrentContext.Channels on m.ChannelId equals ch.ChannelId
                                   join chg in SessionHandler.CurrentContext.ChannelGroups on ch.ChannelGroupId equals chg.ChannelGroupId
                                   join tchg in SessionHandler.CurrentContext.ChannelGroups on chg.ParentChannelGroupId equals tchg.ChannelGroupId
                                   where tchg.ParentChannelGroupId == model.LoggedChannelGroupId
                                   select ls).ToList();

ls包含Score1、Score2、Score3、Score4。所有这些都是数据库中的varchar(50)。此外,它们也允许空值。

如果我需要得到Score1的平均值并将其传递给我的模型数据,我该如何做呢?

我尝试了model.AvgScore1 = _districtResult.Select(m => m.Score1).Average().Value。但是我在这样做的时候遇到了一个错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-30 03:06:26

您必须(在本例中)将m.Score1转换为数值类型(here is the MSDN documentation for the Average method。不能对字符串数据运行数学函数。您可能还应该检查是否为空。

大致是这样的:

代码语言:javascript
复制
_districtResult.Select(m => string.IsNullOrEmpty(m.Score1) ? 0 : //null, use 0
                            Double.Parse(m.Score1)).Average()    //to double
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5836195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档