【问题标题】:Can iEqualityComparer be used to keep one object over anotheriEqualityComparer 可以用来将一个对象保持在另一个对象之上吗
【发布时间】:2014-03-11 02:35:58
【问题描述】:

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

对象:

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

比较器:

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 来做到这一点,或者我应该使用不同的方法吗?

【问题讨论】:

  • 你不能用相等比较器做到这一点(我实际上并不认为你可以在 linq-to-entities 中使用自定义比较器,我相信它会像常规 linq-to 一样运行-对象)。您可以先对项目进行分组,然后从每个组中选择一个您最喜欢的项目(如果不使用自定义比较器,您甚至可以做 SQL 方面)。
  • @AlexeiLevenkov 我相信您对 linq-to-objects 的看法是正确的,这就是为什么我必须在使用 Distinct 之前列出结果。你能提供一个使用分组来达到预期结果的例子吗?

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


【解决方案1】:

【讨论】:

  • 首先感谢您的回复,但来自网站上提供的文档:'尽管保留了一组已经看到的密钥,但此操作员使用延迟执行并流式传输结果。如果多次看到某个键,则仅返回具有该键的 第一个元素。重点是粗体,我想选择保留哪个元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多