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());
    }
}
jonjohnson
  • 413
  • 1
  • 5
  • 18
  • 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](http://stackoverflow.com/questions/3869601/c-sharp-equals-referenceequals-and-operator) – crush Jan 06 '14 at 13:39
  • 1
    Don't forget to override `GetHashCode()` too – Rui Jarimba Jan 06 '14 at 13:43
  • @crush It was an exercise from school just to get to know the operator overloading. – jonjohnson Jan 06 '14 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. – crush Jan 06 '14 at 13:53

1 Answers1

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).

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459