2014-08-28 53 views
-1
class MasterList 
{ 
    public int ID = int.MinValue; 
    public DateTime LastUpdated = DateTime.MinValue; 

    public MasterList(String sId, String sLastUpdated) 
    { 
     sId = ("" + sId).Trim(); 
     sLastUpdated = ("" + sLastUpdated).Trim(); 
     if (sId != "" && sLastUpdated != "") 
     { 
      ID = Convert.ToInt32(sId); 
      LastUpdated = Convert.ToDateTime(sLastUpdated); 
     } 
    } 
} 

List<MasterList> MostUpdatedListFromDataProvider; 
List<MasterList> LocalDBList; 

如何找到兩個單獨列表中要添加的ID和要更新的ID。需要兩個單獨的清單1.添加新產品2.更新產品。什麼是比較兩個列表的最佳方式<Custom>

我試過這個獲取IDsToUpdate。

public static List<int> IDsToUpdate(List<MasterList> DDF, List<MasterList> DB) 
    { 
     List<int> IDs = new List<int>(); 

     foreach (MasterList ml in DDF) 
     { 
      MasterList q = (from dbb in DB 
          where dbb.ID.Equals(ml.ID) 
          where dbb.LastUpdated < ml.LastUpdated 
          select dbb).SingleOrDefault(); 
      if (q != null) 
      { 
       Console.WriteLine("IDsToUpdate: " + ml.ID); 
       IDs.Add(ml.ID); 
      } 
     } 

     return IDs; 
    } 

但這是超級慢。

+2

什麼是_purpose_這個:'(「」+ sId).Trim();' – 2014-08-28 23:07:27

+0

正確地修剪輸入字符串,因爲輸入數據有很多變化。 – Amit 2014-08-28 23:12:04

+0

@ Selman22我懷疑它是'!string.IsNullOrEmpty(sId)' – barrick 2014-08-28 23:14:49

回答

0

如果你想找出哪些MasterList項目在MostUpdatedListFromDataProvider是不是在LocalDBList,然後得到MasterList實施IEquatable<MasterList>並提供在類的Equals()方法相關的比較(不要忘記重寫GetHashCode ()太):

class MasterList : IEquatable<MasterList> 
{ 
    public int ID = int.MinValue; 
    public DateTime LastUpdated = DateTime.MinValue; 

    public MasterList(String sId, String sLastUpdated) 
    { 
     if (!string.IsNullOrEmpty(sId) && 
      !string.IsNullOrEmpty(sLastUpdated)) 
     { 
      ID = Convert.ToInt32(sID); 
      LastUpdated = Convert.ToDateTime(sLastUpdated);  
     } 
    } 

    public bool Equals(MasterList other) 
    { 
     return (this.ID == other.ID && 
       this.LastUpdated == other.LastUpdated); 
    } 

    public override int GetHashCode() 
    { 
     return this.ID.GetHashCode() * this.LastUpdated.GetHashCode(); 
    } 
} 

注意,這個假設sIdsLastUpdated將轉換爲intDateTime - 你不妨加進一步檢查這一點。

現在,這是在地方,你可以使用Enumerable.Except檢索兩個Lists之間的差異:根據每個List的大小

var differences = MostUpdatedListFromDataProvider.Except(LocalDBList); 

,你可能會發現不同的性能,如果你交換他們周圍如

var differences = LocalDBList.Except(MostUpdatedListFromDataProvider); 

爲一體的List將被完整地讀到內存,而另一種是流,但它可能是更直接的方式不符合您的要求。

相關問題