Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Loop through one list and compare objects

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());
    }
}
like image 884
jonjohnson Avatar asked Mar 10 '26 14:03

jonjohnson


1 Answers

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

like image 181
Sergey Berezovskiy Avatar answered Mar 12 '26 04:03

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!