2011-01-13 11 views
5

Mam coś takiego w obrębie List<object> gdzie object zawiera Cat, Type i Items.dane zagregowane grupowania i dokonywania obliczeń w 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 

Co chcę zrobić, to obliczyć średnie pozycje typów więc produkować coś takiego:

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

Jak widać średnie pozycje są obliczane dla typów Co najlepszym sposobem to zrobić?

+0

można umieścić linię na co struktura danych wygląda? lista krotek? – vlad

+2

@vlad: Założę obiekt o trzech właściwościach. – Joey

+0

przepraszam, tak, lista typu obiektu mająca 3 właściwości – flammable11

Odpowiedz

7

Zakładając, że wkład jest zaopatrzony w zmienną list typu IEnumerable<Blah> (zawierającym, na przykład, wynik zapytania do bazy danych, A List<Blah>, tablicą etc.etc.), A Blah jest klasa pola lub właściwości nazywa Cat, Type i 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); 
    } 
} 
Powiązane problemy