Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - 按对象的所有属性分组(Group by all properties of an object)

I am trying to get a distinct list of object from one that different instances with identical values.

(我正在尝试从具有相同值的不同实例中获取对象的不同列表。)

I have tried to use the distinct and the group by.

(我试图使用与众不同的分组方式。)

I got the group by working, but I don't want to rewrite the function when I update the object.

(我是通过工作来组的,但是我不希望在更新对象时重写函数。)

    // my object: 
    public class dummyObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    [TestMethod]
    public void dummytest()
    {
        // my list:
        var list = new List<dummyObject>
        {
            new dummyObject{ Id = 1, Name = "derp" },
            new dummyObject{ Id = 2, Name = "derp" },
            new dummyObject{ Id = 1, Name = "flerp" },
            new dummyObject{ Id = 1, Name = "derp" },
        };
        // this wont work, unless I override the GetHashCode and Equals function
         var result = list.Distinct(); // count = 4
        Assert.AreEqual(4, result.Count());
        // this will work if I group by all the properties that matter
        var result2 = list
       .GroupBy(x => new { x.Id, x.Name })
       .Select(x => x.First());
        Assert.AreEqual(3, result2.Count());
    }

I don't want to specify all of the properties that matter, since it's possible that more will be added, and i want to keep this low maintenance.

(我不想指定所有重要的属性,因为可能会添加更多的属性,并且我想保持较低的维护成本。)

I know that I'll always want to use all the properties.

(我知道我将一直想使用所有属性。)

Is there a better way of doing what I'm trying to do?

(有没有更好的方式来做我想做的事情?)

Or am I stuck using Group by or overriding the GetHashCode and Equals functions?

(还是坚持使用Group by或覆盖GetHashCodeEquals函数?)

  ask by martijn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will have to make your own Comparator and override the GetHashCode and Equals functions.

(您将必须创建自己的比较器,并重写GetHashCode和Equals函数。)

There is no way around it, the function Distinct cannot on which properties to assert if you don't tell it.

(无法绕开它,如果您不告诉它,函数Distinct将无法对要声明的属性进行声明。)

It is an object and not a primitive after all

(毕竟它是一个对象而不是原始的)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...