过滤C#WPF

时间:2017-09-25 15:25:38

标签: c# wpf entity-framework data-binding

我正在使用C#WPF开发一个应用程序,我正在使用EF6.0框架来处理数据。我对于过滤可观察集合或显示特定属性的不同值的最佳方法感到困惑。我尝试用这段代码做但没有成功。这是尝试过滤唯一SW版本public void getuniquesw()的方法。我检查了Iequality可比较的方法,但无法理解它。什么是最简单的过滤/区分值的方法。

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; }

    }
}

1 个答案:

答案 0 :(得分: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()));
}