2015-11-05 70 views
0

具有兩個數據表如下使用LINQ .NET

dtOne 
------------------------- 
    ID | Name | Qty 
-------------------------- 
101 | ABC | 1 
102 | XYZ | -1 
102 | MNO | 1 
103 | def | 1 
-------------------------- 

dtTwo 
------------------------- 
    ID | Name | Qty 
-------------------------- 
    102 | XYZ | -1 
-------------------------- 

只想結果作爲其在dtOne而不是在dtTwo數據中移除兩個表之間的重複行(dtOne-dtTwo)

dtResult 
------------------------- 
    ID | Name 
-------------------------- 
101 | ABC 
103 | DEF 
-------------------------- 

我該如何做到這一點。

我有試過除...但它僅eleiminating「-1」行...我需要數量1行也

回答

0

您可以使用這樣的事情:

var dtTwoIds = dtTwo.Select(element => new {element.ID}).Distinct(); 
var dtResult = dtOne.Where(element => dtTwoIds.All(ids => ids.ID != element.ID)); 
1

也許你需要Enumerable.Except功能。沒有一個現成的解決方案,但你可以在鏈接的這個例子描述嘗試相同:

Product[] fruits1 = { new Product { Name = "apple", Code = 9 }, 
         new Product { Name = "orange", Code = 4 }, 
         new Product { Name = "lemon", Code = 12 } }; 

Product[] fruits2 = { new Product { Name = "apple", Code = 9 } }; 

//Get all the elements from the first array 
//except for the elements from the second array. 

IEnumerable<Product> except = 
    fruits1.Except(fruits2); 

foreach (var product in except) 
    Console.WriteLine(product.Name + " " + product.Code);