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或覆盖GetHashCode
和Equals
函数?)
ask by martijn translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…