C# LINQ Query to Sum Data Groupby Column?
I have a Data View that contains a DATE
Column and a POWER
Column. I am filling this data view from an XML file which I get from a particular link and I want to sum the POWER
Column Group by "DATE". I use this linq query to get it:
var query = from row in _Hdt.AsEnumerable()
group row by row.Field<int>("DATE") into grp
orderby grp.Key
select new
{
DATE = grp.Key,
Sum = grp.Sum(r => r.Field<decimal>("KW"))
};
foreach (var grp in query)
{
Console.WriteLine("{0}\t{1}", grp.Id, grp.Sum);
}
}
but i am getting errors:
Error 1 Invalid token 'return'开发者_JAVA百科 in class, struct, or interface member declaration
Error 2 Invalid token ';' in class, struct, or interface member declaration
Error 3 Expected class, delegate, enum, interface, or struct
Error 4 Expected class, delegate, enum, interface, or struct
Error 5 Expected class, delegate, enum, interface, or struct
Error 6 Identifier expected C:\Documents and Settings\Administrator.MUSEWERX-
Error 7 Expected class, delegate, enum, interface, or struct
Error 8 Expected class, delegate, enum, interface, or struct
Error 9 A namespace does not directly contain members such as fields or methods
Error 10 Type or namespace definition, or end-of-file expected
I hope for your replies.
The problem is not LINQ query itself but incorrect placing of braces.
Apparently, the compiler decided that your return
statement is right inside of the class declaration. Of course you can't return
from a class, you can only return
from a method.
I can't tell the problem right away because you only posted a piece of your code, however I noticed there are two closing }
instead of just one matching foreach
—could that be the reason compiler thought method is over?
Create a method which returns an IEnumerable
and place your code into it.Do not directly write the code inside the class.
EDIT:
public IEnumerable MethodAmk(){
var query = from row in _Hdt.AsEnumerable()
group row by row.Field<int>("DATE") into grp
orderby grp.Key
select new {
DATE = grp.Key,
Sum = grp.Sum(r => r.Field<decimal>("KW"))
};
foreach (var grp in query)
{
Console.WriteLine("{0}\t{1}", grp.Id, grp.Sum);
}
return query;
}
精彩评论