2011-01-13 33 views
5

que tienen algo como esto dentro de un List<object> donde object contiene Cat, Type y Items.Agrupar datos y hacer cálculos agregados en C#

Cat | Type | Items 
-------------------- 
A | P | 3 
A | Q | 4 
A | R | 2 
A | P | 1 
A | Q | 5 
B | P | 2 
B | Q | 1 
B | R | 3 
B | P | 9 

Lo que quiero hacer es calcular los puntos medios de los tipos de modo de producir algo como esto:

Cat | Type | Items 
-------------------- 
A | P | 2 
A | Q | 4.5 
A | R | 2 
B | P | 5.5 
B | Q | 3 
B | R | 5 

Como se puede ver los elementos promedio se calculan para los tipos ¿Cuál es la mejor manera de ¿para hacer esto?

+0

puede que incluir una línea en lo que la estructura de datos se parece? una lista de tuplas? – vlad

+2

@vlad: Asumiría un objeto con tres propiedades. – Joey

+0

lo siento, sí, la lista del tipo de objeto tiene 3 propiedades – flammable11

Respuesta

7

Suponiendo que la entrada se proporciona en una variable llamada list de tipo IEnumerable<Blah> (que contiene, por ejemplo, un resultado de consulta de base de datos, un List<Blah>, una matriz, etc.etc.), Y que Blah es una clase con campos o propiedades llama Cat, Type y Items:

var result = list.GroupBy(entry => new { entry.Cat, entry.Type }) 
       .Select(group => new { group.Key.Cat, group.Key.Type, 
             Items = group.Average(e => e.Items) }) 
2
class Stuff 
{ 
    public string Cat { get; set; } 
    public string Type { get; set; } 
    public double Items { get; set; } 
} 

static void Main(string[] args) 
{ 
    var list = new List<Stuff>(); 
    list.Add(new Stuff { Cat = "A", Type = "P", Items = 3 }); 
    list.Add(new Stuff { Cat = "A", Type = "Q", Items = 4 }); 
    list.Add(new Stuff { Cat = "A", Type = "R", Items = 2 }); 
    list.Add(new Stuff { Cat = "A", Type = "P", Items = 1 }); 
    list.Add(new Stuff { Cat = "A", Type = "Q", Items = 5 }); 
    list.Add(new Stuff { Cat = "B", Type = "P", Items = 2 }); 
    list.Add(new Stuff { Cat = "B", Type = "Q", Items = 1 }); 
    list.Add(new Stuff { Cat = "B", Type = "R", Items = 3 }); 
    list.Add(new Stuff { Cat = "B", Type = "P", Items = 9 }); 

    var result = from stuff in list 
       group stuff by new { stuff.Cat, stuff.Type } into g 
       select new { Cat = g.Key.Cat, 
           Type = g.Key.Type, 
           AvgItems = g.Average(s => s.Items) }; 

    foreach(var s in result) 
    { 
     Console.WriteLine("{0} | {1} | {2}", s.Cat, s.Type, s.AvgItems); 
    } 
} 
Cuestiones relacionadas