开发者

Average and Sum do not work on anonymous types?

开发者 https://www.devze.com 2023-04-02 18:20 出处:网络
Sorry if this has already been asked somewhere, but I wasn\'t able to find it.It seems that Average and Sum do not work across anonymous types.I\'ve been trying for a while to get this code to work, w

Sorry if this has already been asked somewhere, but I wasn't able to find it. It seems that Average and Sum do not work across anonymous types. I've been trying for a while to get this code to work, with no luck. The query I'm doing is:

var trainingPlan = (from tp in context.TPM_TRAININGPL开发者_如何学编程AN
                    join tpd in context.TPM_TRAININGPLANDELIVERABLES on tp.TRAININGPLANID equals tpd.TRAININGPLANID
                    join t in context.TPM_TASK on tpd.TASKID equals t.TASKID
                    where tp.TPM_PROJECTVERSION.PROJECTID == projectId && tp.TPM_PROJECTVERSION.VERSIONID == versionId && tp.TRAININGPLANTYPE == "prescribed"
                    select new
                    {
                        CourseLength = tp.COURSELENGTHHOUR * 60 + tp.COURSELENGTHMINUTE,
                        DeliveryMethod = tp.TPM_DELIVERYMETHODS.NAME,
                        CourseCode = t.COURSECODE
                    });

I now want to take an sum of the CourseLength property, so I do:

int sum = trainingPlan.Sum(l => l.CourseLength.Value);

However, "sum" ends up being 0. Same with "Average". I can clearly see under the debugger that trainingPlan has two items, one with CourseLength = 90 and one with CourseLength = 150.

Does Sum just not work on these types of enumerables? Thanks!


Definitely this could be an issue with the database provider? Since this is a small collection, and you could do trainingPlan.AsEnumerable().Sum. Or, if you are doing multiple calculations, do trainingPlan.ToList(), store that and use it in your calculations.


This works fine:

class Program {
    static void Main(string[] args) {
        var stuff = from i in new double[] { 1, 2, 3 }
                    select new {
                        Value = (int) i,
                    };

        var sum = stuff.Sum( s => s.Value);
        Console.WriteLine(sum);
    }
}

so try :

select new
                    {
                        CourseLength = (int) tp.COURSELENGTHHOUR * 60 + tp.COURSELENGTHMINUTE,
                        DeliveryMethod = tp.TPM_DELIVERYMETHODS.NAME,
                        CourseCode = t.COURSECODE
                    });

and int sum = trainingPlan.Sum(l => l.CourseLength);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号