tags:

views:

58

answers:

1

Hi,

I'm having a problem with a LINQ expression.

With this class:

class MyClass
{
    public string of { get; set; }
    public string order { get; set; }
    public int qty { get; set; }

    public override string ToString()
    {
        return string.Format("OF: {0}, Order: {1}, Qty: {2}", of, order, qty);
    }
}

and I want to sum all qty by OF and by ORDER With this data:

 var list = new List<MyClass>();
 list.Add(new MyClass { of = "of1", order = "order1", qty = 1 });
 list.Add(new MyClass { of = "of1", order = "order1", qty = 9 });
 list.Add(new MyClass { of = "of2", order = "order1", qty = 30 });
 list.Add(new MyClass { of = "of1", order = "order2", qty = 100 });

it should return

OF: of1, Order: order1, Qty: 10
OF: of2, Order: order1, Qty: 30
OF: of3, Order: order2, Qty: 100

I have this solution, but I don't like it

 var sum = from p in list
                  group p by p.of+","+p.order
                  into g
                  select new MyClass
                             {
                                 of = g.Key.Split(',')[0],
                                 order = g.Key.Split(',')[1],
                                 qty = g.Sum(p=>p.qty)
                             };
+2  A: 

You could use an anonymous type as your key:

 var sum = from p in list
                  group p by new { Of = p.of, Order = p.order }
                  into g
                  select new MyClass
                             {
                                 of = g.Key.Of,
                                 order = g.Key.Order,
                                 qty = g.Sum(p=>p.qty)
                             };
adrift
Is that simple :O. Thank you adrift
muek