C# <LIST> 如何检查列表中的非唯一值?

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

这是构造函数(它是完整的,但这里我只显示第一行):

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

节目:

Player player1 = new Player("Mike","Dalton", md@mail.com);
Player player2 = new Player("Mario","Davis", mdavis@mail.com);
Player player3 = new Player("Mia","Duncan", md@mail.com);
...

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

列表中有 3 位玩家。真正的名单很长。需要检查是否所有电子邮件地址都是唯一的。
(如你所见:email_player1 = email_player 3)

最后,一个简单的消息(console.writeline)应该告诉是否有email_doubles。

你能帮帮我吗?

您可以尝试以下方法:

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

如果你想专门显示重复的邮件地址也可以试试下面的方法:

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.");
   }
}

试试这个... 这将为您提供列表中存在的所有重复电子邮件的列表。

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

Select(...) 将帮助您获取列表中元素的属性。

Distinct() 将帮助您使列表包含列表中的独特元素。

如果你想检查所有元素是否唯一,你可以使用:

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

有:

  • players.Distinct().Count():计算唯一元素。
  • players.Count():统计列表元素。
  • 如果它们相同(isUnique = true),则列表中的所有元素都是唯一的。

如果您认为电子邮件地址就像数据库的键 table 因为它是唯一的并且只想存储每个 key/e-mail 之一,那么列表可能不是最好的集合.

您可以改用 HashSet,它只接受唯一项。

参见 Microsoft 文档:https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?redirectedfrom=MSDN&view=net-5.0

你这样声明

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

当您尝试添加它时,它会 returns 从真到假取决于它是否被接受(唯一)。

添加到集合:

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

为了检查唯一性,您需要在 IEquatable<T> 中实施您的 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);
    }
}

作为一个基本的方法,你可以像下面这样:

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);
}