C#检查重复项的对象数组

1 c# arrays dictionary no-duplicates

我有一个Customer []对象数组,我想用它来创建Dictionary <Customer,string>.在加载Dictionary之前,检查重复数组的最简单方法是什么?我想避免"ArgumentException:已经添加了具有相同键的项目".谢谢.

Jan*_*ter 6

在添加Customers之前,只需调用Dictionary.ContainsKey(key).


LBu*_*kin 5

你可以使用LINQ来做到这两点:

Customer[] customers; // initialized somehow...
var customerDictionary = customers.Distinct().ToDictionary( cust => cust.SomeKey );
Run Code Online (Sandbox Code Playgroud)

如果你将以一种不太直接的方式构建字典,你可以使用Distinct()扩展方法来获得一个独特的数组,如下所示:

Customer[] uniqueCustomers = customers.Distinct().ToArray();
Run Code Online (Sandbox Code Playgroud)

如果您需要了解潜在的重复项,可以GroupBy( c => c )先使用它来确定哪些项目有重复项.

最后,如果您不想使用LINQ,您可以动态构建字典并在添加每个项目时使用前置条件检查:

var customerDictionary = new Dictionary<Customer,string>();
foreach( var cust in customers )
{
    if( !customerDictionary.ContainsKey(cust) )
        customerDictionary.Add( cust, cust.SomeKey ); 
}
Run Code Online (Sandbox Code Playgroud)