我需要从下面的linq查询中获得平均值,但数据字段是varchar,这样做时我得到了错误。
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。但是我在这样做的时候遇到了一个错误。
发布于 2011-04-30 03:06:26
您必须(在本例中)将m.Score1转换为数值类型(here is the MSDN documentation for the Average method。不能对字符串数据运行数学函数。您可能还应该检查是否为空。
大致是这样的:
_districtResult.Select(m => string.IsNullOrEmpty(m.Score1) ? 0 : //null, use 0
Double.Parse(m.Score1)).Average() //to doublehttps://stackoverflow.com/questions/5836195
复制相似问题