2017-09-25 64 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 :) –