簡體   English   中英

從列表中獲取不同的值 <T> 在C#中

[英]Get Distinct values from List<T> in c#

嗨,程序員! 實際上,在將一些值添加到列表后,我需要列表中的不同值。 我的代碼是這樣的

             List<Employee_Details> Temp = new List<Employee_Details>();
             Temp =(List<Employee_Details>) newform.Tag;
             EMP_DETAILS.Concat(Temp).Distinct();

但是我直接忽略並且不添加值。

請幫幫我。

Distinct傾向於同時為要比較的類型定義GetHashCodeEquals或提供相等比較器。 如果兩個對象具有相同的哈希碼,則將檢查它們是否相等。

您可以為您的類型實現GetHashCodeEquals但是我有時會發現在一種情況下定義相等並不總是適用於所有情況-即在UI情況下,僅檢查兩個對象的ID是否匹配就足夠了,因為UI可能沒有在對象上定義的所有實際可用的相同數據(因此,不能始終滿足單個真正的相等性)。

因此,我更喜歡為Employee_Details實現IEqualityComparer<T>類型,然后將其實例提供給Distinct方法。

public class EmployeeDetailsComparer : IEqualityComparer<Employee_Details>
{
    #region IEqualityComparer<int> Members
    public bool Equals(Employee_Details x, Employee_Details y)
    {
        //define equality
      if(x == null)
      {
        return y == null;
      }
      else if(y == null) return false;
      //now check the fields that define equality - if it's a DB record,
      //most likely an ID field
      return x.ID == y.ID; //this is just A GUESS :)
    }

    public int GetHashCode(Employee_Details obj)
    {
        //define how to get a hashcode
        //most obvious would be to define it on the IDs, 
        //but if equality is defined across multiple fields
        //then one technique is to XOR (^) multiple hash codes together
        //null-check first
        if(obj == null) return 0;
        //now either:
        return obj.ID.GetHashCode();
        //or something like
        return obj.FirstName.GetHashCode() ^ obj.Surname.GetHashCode();
    }

    #endregion
}

現在您可以執行以下操作:

EMP_DETAILS.Concat(Temp).Distinct(new EmployeeDetailsComparer());

盡管注意實際上並沒有做任何事情 -您實際上需要捕獲 Concat方法的返回值(作為IEnumerable<Employee_Details>或“實現”到數組或列表中):

Employee_Details[] result = 
  EMP_DETAILS.Concat(Temp).Distinct(new EmployeeDetailsComparer()).ToArray();

現在,您將其替換為EMP_DETAILS 如果它是List<Employee_Details> ,則可以執行以下操作:

EMP_DETAILS = 
  EMP_DETAILS.Concat(Temp).Distinct(new EmployeeDetailsComparer()).ToList();

實際上,跨多個值實現良好的哈希碼是很棘手的-但^方法在大多數情況下都可以。 目的是確保您為不同的Employee_Details實例獲得不同的哈希碼。

Distinct方法使用包含對象的Equals比較。 如果您在Employee_Details具有Equals的默認實現,則您可能會比較引用。

因此,您必須選擇:

  1. 為您的Employee_Details實現Equals方法
  2. 使用接受IEqualityComparer的Distinct方法的重載

您需要在您的類中實現IEqualityComparer<T> ,並提供自己的GetHashCodeEquals方法。

http://msdn.microsoft.com/en-us/library/ms132040.aspx

class Employee_Details : IEqualityComparer
{
    public int Employee_ID;

    public Employee_Details(int empID)
    {
        Employee_ID = empID;
    }

    public new bool Equals(object x, object y)
    {
        return x.ToString().Equals(y.ToString());
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }

    public override String ToString()
    {
        return Employee_ID.ToString();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM