可以使用iEqualityComparer将一个对象保留在另一个对象上

时间:2014-03-11 02:35:59

标签: c# asp.net-mvc-3 linq-to-entities

我正在使用linq-to-entities来填充对象列表,然后我使用.Distinct(new objectComparer())来获取不同的记录。我想确保某些对象在列表中保留在其他对象上。

对象:

public class Student
{
    public int NSN { get; set; }
    //removed properties not relevant
    public int EnrolmentStatus { get; set; }
}

的Comparer:

public class StudentComparer : IEqualityComparer<Student>
{
    public bool Equals(Student x, Student y)
    {
        //Check whether the properties are equal. 
        return x.NSN == y.NSN;
    }

    public int GetHashCode(Student obj)
    {
        return obj.NSN.GetHashCode();
    }
}

查询:

var students = (from t1 in Entities.Table1
                join t2 in Entities.Table2
                on t1.someID equals t2.someID
                where (new int?[] { 3, 6, 10 }).Contains(t2.EnrolmentStatus)
                select new Student
                {
                    NSN = t1.NSN,
                    EnrolmentStatus = t2.EnrolmentStatus
                }).ToList().Distinct(new StudentComparer());

此代码返回不同的NSN值,但是我想确保EnrolmentStatus为3或6的对象优先于EnrolmentStatus 10.是否有任何方法可以使用iEqualityComparer执行此操作,还是应该使用不同的方法?

1 个答案:

答案 0 :(得分:0)

相关问题