2011-12-21 24 views

回答

2

這裏是我的建議:

var result = dbcrs.Where(item => res.FirstOrDefault(resItem => resItem.Id == item.Id) == null); 
+0

'dbcrs.Where(項目=> res.FirstOrDefault(resItem => resItem.Id.TrimEnd()==項目。[0]的ToString()。TrimEnd ())== null);' – 2011-12-21 08:47:19

+0

請更新答案。很感謝。 – 2011-12-21 08:59:25

1

首先,你需要以查詢對DataTable的rows集合使用AsEnumerable(),則不會在使用!Contains這樣的:

var query = from r in dbcrs.AsEnumerable() 
     where !(from s in res select r.Id) 
       .Contains(r.Id) 
     select r; 
1

一個例子使用Except和IEquatable執行此操作<>

這樣做的好處是您可以定義「Equals」的含義,因此可以使用兩個可能具有相同ID但不相等的列表。

例如你從兩個表中獲取數據,所以Id可以重複,但其他一些屬性定義它們是否相等。

class Crs:IEquatable<Crs> 
     { 
      public int Id { get; set; } 
      public string Description { get; set; } 

      public bool Equals(Crs other) 
      { 
       if (Object.ReferenceEquals(other, null)) 
        return false; 

       if (Object.ReferenceEquals(this, other)) 
        return true; 

       return Id.Equals(other.Id) && Description.Equals(other.Description); 
      } 

      public override int GetHashCode() 
      { 
       int hashId = Id.GetHashCode(); 
       int hashDescription = Description == null ? 0 : Description.GetHashCode(); 
       return hashId^hashDescription; 
      } 

     } 

     internal static void RunMe() 
     { 
      var dataTable = new List<Crs>(){ 
       new Crs{Id=1, Description="First"}, 
       new Crs{Id=2, Description="Second"}, 
       new Crs{Id=5, Description="Fifth"} 
      }; 

      var enumerable = new List<Crs>(){ 
       new Crs{Id=2, Description="Second"}, 
       new Crs{Id=4, Description="Fourth"} 
      }; 

      var distinct = dataTable.Except(enumerable); 

      distinct.ToList().ForEach(d => Console.WriteLine("{0}: {1}", d.Id, d.Description)); 
     } 
0
 DataTable dt = new DataTable(); 
     dt.Columns.AddRange(new DataColumn[] 
     { 
      new DataColumn("Id", typeof(System.Int32)), 
      new DataColumn("Name", typeof(System.String)) 

     }); 

     dt.Rows.Add (new Object[]{1,"Test"}); 
     dt.Rows.Add(new Object[] {2, "Test" }); 



     var l = new Int32[] { 2, 4 }; 


     var l1 = dt.AsEnumerable().Where(p1 => Array.IndexOf(l, p1.Field<Int32>(0))<0).CopyToDataTable(); 

這將返回我們一行因爲DataTable中和陣列都具有一個共同的價值,這只是2。所以出放將是

2,測試

相關問題