TdW
TdW

Reputation: 15

C# <LIST> How to check for non-unique values in the list?

This is the constructor (it's fullpropped, but here I only show 1st line):

Public Class Player (string firstName, string lastName, string email)

Program:

Player player1 = new Player("Mike","Dalton", [email protected]);
Player player2 = new Player("Mario","Davis", [email protected]);
Player player3 = new Player("Mia","Duncan", [email protected]);
...

List<Player> players = new List<Player> { player1, player2, player3};

There are 3 players in the list. The real list is pretty long. There needs to be a check if all email-adresses are unique.
(As you see: email_player1 = email_player 3)

At the end, a simple message (console.writeline) should tell whether or not there are email_doubles or not.

Can you help me out?

Upvotes: 1

Views: 2354

Answers (5)

BerkGarip
BerkGarip

Reputation: 544

As a basic way, you can do like below:

List<string> controlList = new List<string>();
foreach (var player in PlayersInfo)
{
    if (controlList.Contains(player.Email))
    {
        Console.WriteLine("there is a duplicate with" + player.email);
    }
    else
    {
        Console.WriteLine(player.Email)
    }
    controlList.Add(player.Email);
}

Upvotes: 1

Kovid Purohit
Kovid Purohit

Reputation: 288

try this... this will give you list of all the duplicate Emails that exists in the list.

 players.GroupBy(x => x.Email).SelectMany(g => g.Skip(1));

Upvotes: 3

jason.kaisersmith
jason.kaisersmith

Reputation: 9610

If you consider the email address to be like a key of a database table in that it is unique and only want to store one of each key/e-mail then maybe List is not the best collection.

You can instead use HashSet which only accepts unique items.

See Microsoft documentation: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?redirectedfrom=MSDN&view=net-5.0

You declar it like this

HashSet<Player> players = new HashSet<Player>();

When you try to add it, then it returns true to false depending if it was accepted (is unique) or not.

Add to set:

if(players.Add(player))
    Console.Writeline($"Player {player} was added OK");
else
    Console.Writeline($"Player with email {player.Email} already exists in the collection!");

In order to check for uniqueness then you need to implement in IEquatable<T> your class

public class Player:  IEquatable<Player>
{
    public string Email { get; set; }
    //Other properties, Constructor & methods etc.
   
    //It is important to implement GetHashCode!
    public override int GetHashCode()
    {
        return Email.GetHashCode();   
    }
 
    public bool Equals(Player other)
    {
        return this.Email.Equals(other.Email);
    }
}

Upvotes: 1

user3701485
user3701485

Reputation: 315

You can try the following approach:

List<string> emailList = players.Select(x => x.Email).ToList();
if (emailList.Count > emailList.Distinct().Count())
{
   Console.WriteLine("Duplicate email address found.");
}

If you want to display duplicate email addresses specifically then can also try the following approach:

var playersGroupByEmailList = players.GroupBy(x => x.Email).Select(g => new { Email = g.Key, Count = g.Count() });
playersGroupByEmailList = playersGroupByEmailList.Where(x => x.Count > 1).ToList();
if (playersGroupByEmailList.Any())
{
   foreach (var playerGroupByEmail in playersGroupByEmailList)
   {
       Console.WriteLine($"{playerGroupByEmail.Email} is duplicate.");
   }
}

Upvotes: 2

Select(...) will help you get the attribute of the elements in the list.

Distinct() will help you make the list contains unique elements from the list.

If you want to check all elements are unique, you could use:

bool isUnique = players.Select(x => x.Email).Distinct().Count() == players.Select(x => x.Email).Count();

With:

  • players.Distinct().Count(): count the unique elements.
  • players.Count(): count the list elements.
  • If they are same (isUnique = true), then the all the elements in list are unique.

Upvotes: 1

Related Questions