2012-05-06 34 views
1

我有一个表[T1]与此informaions的LINQ to SQL得到一个一对多表列结果作为数组

  1. ID
  2. 用户名
  3. 其他...

第二表[T2]是

  1. ID
  2. 用户名
  3. 名称

关系是从T1一个用户可以有多个T2

我想导致像

  1. ID =数字
  2. 用户ID =数字
  3. 数组[t2.name,t2.name,t2.name]

我的灵到SQL就像

var result = (from t1 in context.t1 
       join t2 in context.UserID on t1.ID equals t2.UserID 
       select new CLASS 
       { 
        ID = t1.ID, 
        UserID = t1.UserID, 
        Names = t2.name 
       }).Take(10).ToList(); 

但是,这给我造成每个t2.name作为单独的一行。我如何收集数组中的所有名字?

LINQ to SQL,ASP.NET C#4.0

回答

0

您不需要使用连接。创建关系B/N在LINQ设计师你的两个LINQ entites的,然后你可以运行这样的查询:

var q = from t in context.t1 
     select new { id = t1.id, names = t1.t2s.Select(t => t.Name).ToArray() }; 
0

你必须将你的结果通过ID /用户名:

var result = (from t1 in context.t1 
       join t2 in context.UserID on t1.ID equals t2.UserID 
       group by new { t1.ID, t1.UserID } into g 
       select new CLASS 
       { 
        ID = g.Key.ID, 
        UserID = g.Key.UserID, 
        Names = g.ToArray() 
       }).Take(10).ToList(); 

然而当LINQ to SQL类准备正确的类型的查询可以像进行:

var result = from t1 in context.t1 select new { id = t1.id, names = t1.t2s.ToArray() }; 
1

我觉得这样的事情应该工作

var result = (from t1 in context.t1 
       join t2 in context.UserID on t1.ID equals t2.UserID 
       select new CLASS 
       { 
        ID = t1.ID, 
        UserID = t1.UserID, 
        Names = (from t2 in context.t2 
          select t2.Name 
          where t2.userID = t1.userID).toArray(), 
       }).Take(10).ToList(); 

希望它有帮助