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());
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With