2011-04-29 105 views
0

我需要从下面的linq查询得到一个平均值,但数据字段是varchar,我在得到这个错误的时候出错了。从linq查询得到平均值

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。但我得到一个错误,而这样做..

+2

如果你要问其中包含错误的问题,*总*说的是什么错误,否则它是去看医生,相当于和。只是说,“它伤害了”而不说*什么*伤害。 – 2011-04-29 19:01:33

+1

**它们不应该是'VARCHAR(50)'**。这就像存储玩具自行车在一个全尺寸的停车位。 – SLaks 2011-04-29 19:09:26

回答

0

你必须转换(在你的例子中)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 double 
+0

非常感谢!我试着做_districtResult.Average(m => Convert.ToInt32(m.Score1)); – bladerunner 2011-04-29 19:30:07

+0

你有一个更好。 – bladerunner 2011-04-29 19:30:31