learningdb
learningdb

Reputation: 169

Supply a name to anonymous and call later in LINQ

I have an 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.

Upvotes: 0

Views: 105

Answers (3)

digEmAll
digEmAll

Reputation: 57210

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]) };

Upvotes: 3

hungryMind
hungryMind

Reputation: 6999

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};

Upvotes: 0

satnhak
satnhak

Reputation: 9861

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().

Upvotes: 0

Related Questions