2

how do I compare objects in one list? I have overloaded the operator == which compares two strings :

public static bool operator ==(User one, User two)
{
    return one.Email == two.Email;
}

And i should go through the list comparing beetween them. I have already come up with a solution, which does the job, but I was hoping if there is a better way to do this, using LINQ or lambda expressions.

foreach (User u in up)
{
    foreach (User u2 in up)
    {
        if (ReferenceEquals(u, u2)) continue;
        if (u == u2) Console.WriteLine("Users {0} and {1} have the same mail.", u.ToString(), u2.ToString());
    }
}
4
  • 4
    Overloading operators is almost never a good idea. Especially in this case, I'd say. Add an Equals() method to your User class. See this StackOverflow Q&A Commented Jan 6, 2014 at 13:39
  • 1
    Don't forget to override GetHashCode() too Commented Jan 6, 2014 at 13:43
  • @crush It was an exercise from school just to get to know the operator overloading. Commented Jan 6, 2014 at 13:47
  • 1
    @jonjohnson Inform your professor that he needs to choose a more relevant example from which to teach operator overloading. Teaching students with examples that only instill bad practices is never a good idea. Commented Jan 6, 2014 at 13:53

1 Answer 1

9

You can use grouping without any operators overloading (which is bad idea I think):

var userGroups = up.GroupBy(u => u.Email).Where(g => g.Count() > 1);

foreach(var group in userGroups)
{
    Console.WriteLine("Following users have email {0}", group.Key);

    foreach(var user in group)
       Console.WriteLine(user);
}

Query is simple - it groups users by email, and selects groups where more than one user (i.e. those users have same email).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.