2017-06-27 40 views
-2

我在做一個除了兩個DataTable的替代方式。我已超負荷的IEqualityComparer最快方式或自定義的枚舉計數元件鍵入C#

public bool Equals(T sourceRec, T targetRec) 
    { 
     string srcHash, tgtHash; 
     srcHash = HashGenerator.GenerateHash<T>(sourceRec); 
     tgtHash = HashGenerator.GenerateHash<T>(targetRec); 
     return srcHash.Equals(tgtHash); 
    } 

    public int GetHashCode(T obj) 
    { 
     return base.GetHashCode(); 
    } 

和除了將通過考慮每個DataRow的哈希值的工作。

public class CompareResult<T> 
    { 
     public IEnumerable<T> Inserted_Updated; 
     public IEnumerable<T> Updated; 
     public IEnumerable<T> Deleted; 
    } 

public CompareResult<DataRow> Compare(DataTable source, DataTable target) 
     { 
      CompareResult<DataRow> rest = new CompareResult<DataRow>(); 
      rest.Inserted_Updated = target.AsEnumerable().Except(source.AsEnumerable(), RowHashComparer); 
      rest.Deleted = (source.AsEnumerable().Except(target.AsEnumerable(), RowHashComparer)).Except(target.AsEnumerable().Except(source.AsEnumerable(), RowHashComparer)); 

      return rest; 
     } 

CompareResult<DataRow> strResult = SD1.Compare(src, tgt); 

RowHashComparer是用來執行自定義屬性,除了通過比較哈希代碼。 我追查的是等式比較在Except方法返回後實際發生。

請建議。

+0

而不是返回一個'Enumerable',你可以返回'的HashSet <> '。 – Rob

+3

我有一個裝滿彈珠的包,我想知道我有多少個彈珠。你能告訴我一種不涉及*一個一個地計算*的方法嗎?呃,不,不是。也許你應該退後一步,問自己一袋是你真正需要的。其他類型的收藏品是否做得更好? – InBetween

+1

@InBetween - 貨幣可以通過加權來計算。標準化的大理石在一個已知重量的袋子裏可以用一個比例來計數。 – Moho

回答

-3

最簡單的形式是:

public static int Count(this IEnumerable source) 
{ 
    int c = 0; 
    using (var e = source.GetEnumerator()) 
    { 
     while (e.MoveNext()) 
      c++; 
    } 
    return c; 
} 

,我們可以通過查詢ICollection這個再提高:

public static int Count(this IEnumerable source) 
{ 
    var col = source as ICollection; 
    if (col != null) 
     return col.Count; 

    int c = 0; 
    using (var e = source.GetEnumerator()) 
    { 
     while (e.MoveNext()) 
      c++; 
    } 
    return c; 
} 
+2

這改善'Enumerable.Count (這IEnumerable的源)做這個存儲過程'究竟如何? – InBetween

+1

@Rohit - 檢查C#中的最新語法糖: if(source is ICollection col) { return col.Count; } – Moho

+0

@莫霍感謝您的建議..我正在努力。 –