Mark Benovsky Mark Benovsky - 3 months ago 19
C# Question

What methods should I override to use LINQ Where, Find?

Here is some example code.

I have created my own class:

public class MyObject {
private string _guid;
public int Value;

// other stuff here...

public MyObject() {
_guid = Guid.NewGuid().ToString();

And i have some object i created before and a list of other objects, for example:

MyObject inputObject = new MyObject();
List<MyObject> myObjects = new List<MyObject>();

I want to use them like:

myObjects.Where(mo => mo == inputObject).Sum(fo => fo.Value);

And so on. (I am sure that in my list there is an object with the same GUID as the inputObject, this is just the example code)

The questions are:

How can I use LINQ Find, Where, Sum and so on on this List?

What methods should i override to compare by GUID and how should they look like?

Is it better to use IEquatable with Equals() method?


Since you're checking with ==, you would need to provide the == operator (which also means you need to provide a != operator). Otherwise, reference equality will be applied (since it is a class), and : it is unlikely that it is the same object (just one that is equivalent).

Alternatively, you could override Equals and change your test to use .Equals (note: also override GetHashCode() if you do this).

An easier option, however, might be to check the relevant inner value directly, i.e.

public string Guid => _guid;


.Where(mo => mo.Guid == inputObject.Guid)