You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用fluent-assertions断言集合中所有元素互不相同

Fluent Assertions判断集合元素全部唯一的实现方式

你可以直接使用Fluent Assertions内置的OnlyHaveUniqueItems()方法完成校验,该方法的设计用途就是验证集合内不存在重复元素。

你提供的示例可以改写为如下代码,注意非泛型的IEnumerable需要先转为泛型集合再调用方法:

IEnumerable collection = new[] { 1, 2, 5, 8 };
collection.Cast<int>().Should().OnlyHaveUniqueItems();

如果是泛型集合可以直接调用:

IEnumerable<int> collection = new[] { 1, 2, 5, 8 };
collection.Should().OnlyHaveUniqueItems();

如果是自定义类型的集合,也可以指定去重的匹配规则,比如按对象的Id属性判断是否重复:

// 假设Person类存在Id属性
IEnumerable<Person> personList = GetPersonList();
personList.Should().OnlyHaveUniqueItems(p => p.Id);

如果你使用的是6.0以下的旧版本Fluent Assertions(该版本才正式加入OnlyHaveUniqueItems方法),可以用如下替代方案:

IEnumerable collection = new[] { 1, 2, 5, 8 };
var castCollection = collection.Cast<int>();
castCollection.Distinct().Count().Should().Be(castCollection.Count());

内容的提问来源于stack exchange,提问作者Albert Takács

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:27:00