tags:

views:

27

answers:

1

The scenario is like this:

name | val  
'aa' | 10
'bb' | 20
'cc' | 30
*********
sum  | 60

For now I just select all the records in simple LINQ query and invoke the enumerator (ToList())

Then I loop over the list and summarize the val column.

Is there a better way? LINQ selects all to a new typed object so I dont know how to add the additional data.

thanks.

+2  A: 

Anonymous type cant allow value to be added or edited once its created. so instead of returning anonymous type, you can use your custom output class. Something like this

        public class ResClass
        {
            public string name;
            public int value;
        }

        public class OutClass
        {
             public int sum;
             public List<ResClass> lstData;
        }

        int sum=0;
        var outtt = objTT.Where(x => x.id == 1).Select(x =>
        {
            sum += x.value;
            return new ResClass { name =  x.name, value= x.value };

        }).ToList();

        OutClass outCls = new OutClass { sum = sum, lstData = outtt };
Ramesh Vel
thanks for the replay.the "sum += x.value;" is new way for me. is there is some way todo this with from x in y select.. style?
ari
@ari, "sum += x.value" is nothing but "sum=sum+x.value", which means it adds up the x.value on each iteration to calculate the sum..
Ramesh Vel
i dont think we cant do that in "from x in y style", well i am not sure.. since am using anonymous methods, its the way to do that... well atleast
Ramesh Vel
@Ramesh Vel, yes i familier with += approuch.the option to include "out of context" command in the selectis new for me. i'am always working with "from x in y style"..
ari