2010-08-11 71 views

回答

1

這聽起來像你希望TableA和TableB的兩個實體合併成一個新的對象。您可以使用.Select()擴展方法創建一個新的匿名類型,或者創建一個您已經定義的類。

這裏的要求是你必須在TableA和TableB之間找到一個共同的屬性。在這裏,我假設你有類似ID的東西來匹配它們。

匿名類型

var mergedTests = from a in db.TableA 
        join b in db.TableB on a.CommonID equals b.CommonID 
        select new 
          { TestFromA = a.Test, TestFromB = b.Test } 
        .ToList(); 

現有類

List<MyCustomTests> mergedTests = from a in db.TableA 
        join b in db.TableB on a.CommonID equals b.CommonID 
        select new MyCustomTests 
         { TestName= a.Test, ShortName= b.Test } 
        .ToList(); 
+0

這不是我想要的,我想從表A和B中選擇列Test到同一行,但列名不同。例如。 TestA和TestB在同一行。 – Anonymous 2010-08-11 04:31:29

0
class Program 
{ 
    static void Main(string[] args) 
    { 
     var A = new Data[] { 
      new Data { Test = 1, Relation = 1 }, 
      new Data { Test = 2, Relation = 2 }, 
      new Data { Test = 3, Relation = 3 }, 
      new Data { Test = 4, Relation = 4 }, 
      new Data { Test = 5, Relation = 5 }, 
     }; 

     var B = new Data[] { 
      new Data { Test = 2, Relation = 2 }, 
      new Data { Test = 3, Relation = 3 }, 
      new Data { Test = 5, Relation = 5 }, 
     }; 

     var res = from a in A 
        join b in B on a.Relation equals b.Relation 
        select new { TestA = a.Test, TestB = b.Test }; 
    } 
} 

class Data 
{ 
    public int Test; 
    public int Relation; 
} 
相關問題