2016-10-04 399 views
-1

我有2個DataTable。一個代表客戶,另一個代表CustomerContacts。C#DataTable查找不存在於另一個DataTable中的行

我需要找到所有沒有任何CustomerContact行的Customer行。

除了有2個循環,並使用DataViews和FindRows來查找哪些客戶沒有任何聯繫人之外,是否有更簡單的代碼方式?我不熟悉LINQ,不希望將其用於當前項目。

我使用.NET 4.5

我不能直接使用SQL數據庫時,因爲沒有「數據庫」。我通過自定義讀取Excel文件來填充DataTables。

+0

不是你的問題的答案,但你真的*應該*開始熟悉LINQ。即使是最簡單的任務,它也成爲標準,並且幾乎可以在任何代碼庫中找到。甚至微軟推動它的使用(一個例子是TypeInfo類和它的屬性的過濾) – pinkfloydx33

回答

0

可以實現這一點,如下使用LINQ(一個& b爲兩個數據表)

var query = (from x in a.AsEnumerable() 
      join y in b.AsEnumerable() on x.Field<int>("col1") equals y.Field<int>("col1") 
      select new { col1= y.Field<int>("col1"), col2=x.Field<int>("col2") }).ToList(); 
1

嘗試下面的代碼。它不使用任何LINQ。將customerID替換爲表格的實際Id列。

DataTable Customers = new DataTable();//fill this table from db 
DataTable CustomersContacts = new DataTable();//fill this table from db 
List<string> NoContactCus = new List<string>(); 
foreach (DataRow Customer in Customers.Rows) 
{ 
    DataRow[] contacts = CustomersContacts.Select(string.Format("customerID={0}", Customer["customerID"].ToString())); 
    if (contacts.Count() == 0) 
     NoContactCus.Add(Customer["customerID"].ToString()); 
} 
0

LINQ是你的朋友。

var result = dtCustomers.AsEnumerable().Select(row => (int)row["id"]) 
    .Except(dtCustomerContacts.AsEnumerable().Select(row => (int)row["customerId"])); 


dtCustomersdtCustomerContacts是數據表,
"id""customerId"是主鍵和外鍵(假定它們是int),
result是客戶ID列表中沒有任何接觸。

+0

與編寫自己的2循環和使用FindRows相比,性能會好還是壞? – AllSolutions

相關問題