使用Linq在对象中的多个集合

时间:2014-03-19 20:08:58

标签: c# linq lambda

我有以下对象

public class bizObj
{
    public string name { get; set; }
    public int p_id { get; set; }
    public string acc_number { get; set; }
    public string a_name { get; set; }
    public string a_phone { get; set; }
    public virtual product product { get; set; }
    public virtual account account { get; set; }
}

从db获取数据的Linq语句是

 public IEnumerable<bizObj> GetbizObj(int id)
        {
            var acs = (from c in db.p_account
                            where c.p_id==id
                            select new bizObj
                            {    
                                name = c.p_name,
                                p_id = c.product.id,
                                acc_number=c.account.acc_number,
                                a_name = c.a_name,
                                a_phone = c.a_phone
                            });    
                       return acs;
        }

上面的代码工作正常,但它返回一个集合。我想要的是什么 得到的是它有一个

的集合
 {
     name,
     p_id
//than a second collection which has all the records that have same name ane p_id
         {
               acc_number,
               a_name
               a_phone
          }
       }

请告诉我如何使用linq / lambda表达式完成此操作。谢谢

1 个答案:

答案 0 :(得分:2)

问题不清楚,但您似乎想要按namep_id对行进行分组。

var query = acs.GroupBy(x => new { x.name, x.p_id })
    .Select(g => new { g.Key.name, g.Key.p_id, Items = g.ToList() });