MyObject have two property named p1 and p2 in int type ;now I want for each of MyObject take p1 and p2 and add those up. I tried this:

int p1Sum = 0, p2Sum = 0;
foreach (int[] ps in new MyEntity().MyObject.Select(o => new { o.p1, o.p2 }))
       {
            p1Sum += ps[0];
            p2Sum += ps[1];   
       } 

but says:

cannot convert AnonymousType#1 to int[]

on foreach.

How can I fix this?

有帮助吗?

解决方案

foreach (var ps in new MyEntity().MyObject.Select(o => new { o.p1, o.p2 }))
       {
            p1Sum += ps.p1;
            p2Sum += ps.p2;   
       } 

其他提示

jyparask's answer will definitely work, but it's worth considering using Sum twice instead - it will involve two database calls, but it may (check!) avoid fetching all the individual values locally:

var entities = new MyEntity().MyObject;
var p1Sum = entities.Sum(x => x.p1);
var p2Sum = entities.Sum(x => x.p2);

Now there's at least logically the possibility of inconsistency here - some entities may be removed or added between the two Sum calls. However, it's possible that EF will ensure that doesn't happen (e.g. via caching) or it may not be relevant in your situation. It's definitely something you should think consider.

In addition to Jon Skeet and jyparask answer you can also try :

var result = (new MyEntity().MyObject
             .GroupBy(_=> 0)
             .Select(r=> new 
                   {
                    p1Sum = r.Sum(x=> x.p1)
                    p2Sum = r.Sum(x=> x.p2)
                   })
             .FirstOrDefault();

The above would result in a single query fetching only Sum for both columns, You may look at the query generated and its execution plan if you are concerned about the performance.

if(result != null) 
  {
   Console.WriteLine("p1Sum = " + result.p1Sum);
   Console.WriteLine("p2Sum = " + result.p2Sum);
  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top