There are several ways to do this, depending on how you generally want to use the instances of your MyObject
class.
The easiest one is implementing the IEquatable<T>
interface so as to compare only the protocol
fields:
public class MyObject : IEquatable<MyObject>
{
public sealed override bool Equals(object other)
{
return Equals(other as MyObject);
}
public bool Equals(MyObject other)
{
if (other == null) {
return false;
} else {
return this.protocol == other.protocol;
}
}
public override int GetHashCode()
{
return protocol.GetHashCode();
}
}
You can then call Distinct
before converting your enumerable into a list.
Alternatively, you can use the Distinct
overload that takes an IEqualityComparer
.
The equality comparer would have to be an object that determines equality based on your criteria, in the case described in the question, by looking at the protocol
field:
public class MyObjectEqualityComparer : IEqualityComparer<MyObject>
{
public bool Equals(MyObject x, MyObject y)
{
if (x == null) {
return y == null;
} else {
if (y == null) {
return false;
} else {
return x.protocol == y.protocol;
}
}
}
public int GetHashCode(MyObject obj)
{
if (obj == null) {
throw new ArgumentNullException("obj");
}
return obj.protocol.GetHashCode();
}
}