LInq到SQl问题....请帮忙

时间:2009-09-16 14:57:45

标签: c# linq-to-sql

我有以下数据

ProductId Description cost
12        test        0.0

12        test        8.8

12        test        7.9

27        asdf        9.0
27        asdf        2.0
27        asdf        2.0

我想要以下结果

12  test 0.0 / test8.8/test 7.9
27  asdf 9.0/asdf 2.0/ asdf 2.0

到目前为止,我只能想出这个......有人指出我正确的方向

非常感谢

var n = from c in query
             group new {c}
             by new
             {
                   c.productid,
                   c.cost,
                   c.prodescription
              }
              into g

              select new{
                                    g.Key.productid,
                                    Products=(g.Key.prodescription) +        g.Key.cost.ToString()),
                                 };

1 个答案:

答案 0 :(得分:4)

var groups = from result in query
             group result by new { result.ProductId } into g
             select g;

foreach(var group in groups) {
    Console.Write("{0}: ", group.Key.ProductId);
    Console.WriteLine(String.Join("/", group.Select(p => String.Format("{0}, {1:0.0}", p.Description, p.Cost)).ToArray()));
}

更好的方法是按照

的方式提供Product.ToString的实现
public override ToString() {
    return String.Format("{0}, {1:0.0}", this.Description, this.Cost);
}

并用

替换上面的Console.WriteLine
Console.WriteLine(String.Join("/", group.Select(p => p.ToString()).ToArray()));