Supply a name to anonymous and call later in LINQ
I have an开发者_如何学JAVA int[] array = {34,65,3,65,3,2,68,8,4,2}. I want to divide this array into group of 5 and find average of each subgroup.
This syntax declares (implicitly) an array of the type returned by Avg()
method:
new [] { Avrg = g.Avg() } // if g.Avg() returns int, it will be int[]
if you want to declare an array of anonymous types, you must do:
new[] { new { Avrg = g.Avg() } }
EDIT:
according to your edit, this code splits the array in groups of 5 elements and computes the average of them:
int[] array = { 34, 65, 3, 65, 3, 2, 68, 8, 4, 2 };
var avgGroups = from x in Enumerable.Range(0, array.Length)
group x by (x / 5) into g
select new { Avrg = g.Average(x => array[x]) };
You don't need to give it a name; the object you are creating is of type
IEnumerable<typeof(g.Avg)>
so you can enumerate through that object to get the value of g.Avg().
Probably you want to store type in array. For this you need to have like this
var v = from xyz in new [] { new {Avg = g.Avg()} }
select xyz;
Rather use this way,
var v = from xyz in new [] { g.Avg() }
select new {Avg = xyz};
精彩评论