我有三个相同模型的集合,只是更改了它们的名称。
想要检查三个列表以便:
1) 如果任一列表中的元素已经在另一个突发中,则出错
2) 当我尝试验证 Any 不接受空值时。
他们如何接受字符串为空?
但我做不到。
我哪里错了?
item.Requeridos > ICollection<MeetingUser>
item.Informados > ICollection<MeetingUser>
item.Opcionais > ICollection<MeetingUser>
public static ValidationResult validaUsuariosNaLista(Reuniao item)
{
var requeridos = item.Requeridos.Select(x => string.IsNullOrWhiteSpace(x.Login)).Any();
var informados = item.Informados.Select(x => string.IsNullOrWhiteSpace(x.Login)).Any();
var opcionais = item.Opcionais .Select(x => string.IsNullOrWhiteSpace(x.Login)).Any();
if (item.Requeridos.Count() + item.Informados.Count() + item.Opcionais.Count() > item.Requeridos.Concat(item.Informados).Concat(item.Opcionais).Distinct().Count())
{
return new ValidationResult(Resources.Validations.sameUserInOtherList);
}
return ValidationResult.Success;
}
请您参考如下方法:
where I am going wrong?
Distinct 的工作方式。根据MSDN
The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.
The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you must implement this interface and provide your own GetHashCode and Equals methods for the type.
在您的情况下,您有一个自定义数据类型,MeetingUser
What can you do?
如果你避免使用Distinct,你可以试试下面的方法:
// Initially you concat the three list to one list
var combinedLists = (item.Requeridos.Concat(item.Informados)).Concat(item.Opcionais);
// Then you group them by the Login. If there is any group with more that 1
// element then you have the same login more that one time.
var result = combinedLists.GroupBy(x=>x.Login)
.Any(gr=>gr.Count()>1);
否则,如果您坚持使用 Distinct,则必须实现 IEquatable 接口(interface)。
