2012-05-06 70 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(); 

希望它有幫助