2017-09-25 127 views
1

我正在C#WPF中開發應用程序,並且我正在使用EF6.0框架來處理數據。我很困惑什麼是過濾可觀察集合或顯示特定屬性的不同值的最佳方式。我試着用這段代碼做,但沒有取得成功。這是試圖過濾獨特的SW版本public void getuniquesw()的方法。我檢查了不平等可比較的方法,但無法理解它。什麼是最簡單的方法來做過濾/獨特的價值觀。實體類的在C#中過濾可觀察的集合WPF

public List<CREntity> crentities 
{ 
    get; 
    set; 
} 

// Obeservable collection property for access 
private ObservableCollection<CREntity> _CRmappings2 = new ObservableCollection<CREntity>(); 
public ObservableCollection<CREntity> CRmappings2 
{ 
    get { return _CRmappings2; } 
    set 
    { 
     _CRmappings2 = value; 
     RaisePropertyChanged("CRmappings2"); 
    } 
} 

public void UpdatePopList() 
{ 
    CRmappings2 = new ObservableCollection<CREntity>(crentities.Where(p => p.MU_Identifier == selectmu.ToString()).ToList()); 
} 

public void getuniquesw() 
{ 

    CRmappings2 = new ObservableCollection<CREntity>(crentities.Select(p=>p.SW_Version).Distinct()); 
} 

定義

using DataModel; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace BusinessEntities 
{ 
    public class CREntity 
    { 
     public long C_ID { get; set; } 
     public string LogName { get; set; } 
     public string xSCR_BUG { get; set; } 
     public string RequestType { get; set; } 
     public string MU_Type { get; set; } 
     public long CPC2_OBD_1Byte { get; set; } 
     public long INS_OBD_1Byte { get; set; } 
     public string MU_Identifier { get; set; } 
     public string Old_MU { get; set; } 
     public int? SPN { get; set; } 
     public int? FMI { get; set; } 
     public string Triggers { get; set; } 
     public string Comment { get; set; } 
     public string Status { get; set; } 
     public string SW_Version { get; set; } 
     public DateTime? Create_Date { get; set; } 
     public DateTime? Upd_Date { get; set; } 
     public virtual ICollection<Fault_Details> FaultDetails { get; set; } 

    } 
} 
+0

我沒有知道有一個明確的問題,任何人都可以幫助你。老實說,你似乎對一些概念有一個基本的誤解。您不清楚您是否瞭解「ObservableCollection」旨在根據您使用它的方式解決的問題。我不確定你完全理解基於你的'getuniquesw'實現的類型。我不確定你如何看待「平等可比方法」。我認爲你需要退一步,找出如何一次解決每個問題。對不起,我無法提供更多幫助。 –

+0

@JasonBoyd謝謝你,我會檢查更多基於類型的實現。 –

+0

@ mm8我添加了定義 –

回答

1

創建一個實現IEqualityComparer<CREntity>類:

public class CREntityComparer : IEqualityComparer<CREntity> 
{ 
    public bool Equals(CREntity x, CREntity y) 
    { 
     if (x != null && y != null && x.C_ID.Equals(y.C_ID)) 
      return true; 

     return false; 
    } 

    public int GetHashCode(CREntity obj) 
    { 
     if (obj == null) 
      return -1; 

     return obj.C_ID.GetHashCode(); 
    } 
} 

...並通過這個實例給Distinct()方法:

public void getuniquesw() 
{ 
    CRmappings2 = new ObservableCollection<CREntity>(crentities.Select(p => p.SW_Version).Distinct(new CREntityComparer())); 
} 
+0

謝謝你的幫助,這很好。所以我應該總是使用Iequalitycomparer,如果我們正在使用可觀察集合,還有其他不同的方法來過濾嗎? –

+0

幾乎所有的事情都有不同的方式。但在這種情況下,您需要定義何時兩個CREntity對象被認爲是相等的。 – mm8

+0

是的,現在我的聲望觸及15,現在我可以upvote :) –