首页 新闻 会员 周边

Linq to Entity 如何按照指定的对象属性来 Distinct

0
悬赏园豆:10 [已解决问题] 解决于 2011-02-12 13:48

Linq to Entity 如何按照指定的对象属性来 Distinct,怎么写。谢谢!

jerry-Tom的主页 jerry-Tom | 老鸟四级 | 园豆:4077
提问于:2010-12-10 11:14
< >
分享
最佳答案
0

直接给你个例子吧,我自己写的代码。           

源数据格式:
 class Example
{
  public int ID { set; get; }
     public string Name { set; get; }

     static List<Example> _instanceList;
     public static List<Example> InstaceList
     {
            get
            {
                if (_instanceList == null)
                {
                    _instanceList = new List<Example>();
                    _instanceList.Add(new Example() { ID = 1, Name = "Jack" });
                    _instanceList.Add(new Example() { ID = 1, Name = "Tom" });
                    _instanceList.Add(new Example() { ID = 2, Name = "Jack" });
                }
                return _instanceList;
            }
        }
}

测试方案:运行

            List<Example> vars = Example.InstaceList;
            var temp = vars.Distinct();

结果,var里面包含了全部数据。

 

修正数据源。让Example继承IEquatable。如下:

    class Example: IEquatable<Example>
    {
        #region IEquatable<Example> 成员

        public bool Equals(Example other)
        {
            // 检查被比较的对象是否为null。
            if (Object.ReferenceEquals(other, null)) return false;
            // 检查是否引用的相同对象。
            if (Object.ReferenceEquals(this, other)) return true;
            // 检查对象的属性是否相等。
            // object.Equlas或==更合适,以免Textual为null时抛出异常。
            // Digital由于是值类型所以不存在这个问题。)
            return ID.Equals(other.ID);
        }

        // 如果比较两个对象是相等的,那么这两个对象的GetHashCode方法必须返回一样的值。
        public override int GetHashCode()
        { return ID.GetHashCode(); }

        #endregion
    }

运行测试方案:

            List<Example> vars = Example.InstaceList;
            var temp = vars.Distinct();

结果,重复ID的消失了。

上面的方法是你可以修改Example类的方法。如果你没有办法修改这个类结构。你可以本地生一个比较器,在distinct方法中作为参数传进去。

代码示例:
 class ExampleComparer : IEqualityComparer<Example>
    {
        public bool Equals(Example x, Example y)
        {
            if (Object.ReferenceEquals(x, y)) return true;
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false;
            return x.ID == y.ID;

        }
        public int GetHashCode(Example example)
        {
            if (Object.ReferenceEquals(example, null)) return 0;
            return example.ID.GetHashCode();
        }
    }

此时测试方案为:           

            List<Example> vars = Example.InstaceList;
            var temp = vars.Distinct(new ExampleComparer());

收获园豆:10
BLoodMaster | 初学一级 |园豆:135 | 2010-12-10 11:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册