用于验证列表顺序是否正确的 lambda 表达式
我想编写一个 lambda 表达式来验证列表的排序是否正确。 我有一个列表,其中一个人有一个 Name 属性,例如:
IList<Person> people = new List<Person>();
people.Add(new Person(){ Name = "Alan"});
people.Add(new Person(){ Name = "Bob"});
people.Add(new Person(){ Name = "Chris"});
我正在尝试测试该列表是否按 Name 属性按 ASC 排序。所以我正在寻找类似
Assert.That(people.All(....), "list of person not ordered correctly");
如何编写 lambda 来检查列表中的每个人列表中的名字小于列表中下一个人的名字?
I want to write a lambda expression to verify that a list is ordered correctly. I have a List where a person has a Name property eg:
IList<Person> people = new List<Person>();
people.Add(new Person(){ Name = "Alan"});
people.Add(new Person(){ Name = "Bob"});
people.Add(new Person(){ Name = "Chris"});
I'm trying to test that the list is ordered ASC by the Name property.So I'm after something like
Assert.That(people.All(....), "list of person not ordered correctly");
How can I write a lambda to check that each Person in the list has a name less that the next person in the list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 Jared 解决方案的替代方案 - 它几乎相同,但使用 foreach 循环和布尔变量来检查这是否是第一次迭代。 我通常发现这比手动迭代更容易:
Here's an alternative to Jared's solution - it's pretty much the same, but using a foreach loop and a Boolean variable to check whether or not this is the first iteration. I usually find that easier than iterating manually:
我不相信目前有任何 LINQ 运算符可以涵盖这种情况。 但是,您可以编写一个 IsOrdered 方法来完成这项工作。 例如。
然后您可以使用以下内容来验证您的列表:
I don't believe there is any LINQ operator which currently covers this case. However you could write an IsOrdered method which does the work. For example.
Then you could use the following to verify your list:
我知道这是一个老问题,但我使用 Linq 有一个非常好的解决方案:
基本上,您将序列与有序序列合并,并投影一个 bool 值来指示两个条目是否相等:
然后使用
All
方法询问集合中的所有项目是否为true
。I know this is an old question, but I have a very nice solution for this using Linq:
Basically, you are merging a sequence with the ordered sequence, and projecting a bool value indicating whether both entries are equal:
Then with the
All
method you ask if all the items in the collection aretrue
.怎么样:
SequenceEqual() 从 3.5 开始可用
如果您想确认没有重复项,可以在 OrderBy() 之后添加 Distinct()。
What about:
SequenceEqual() has been available since 3.5
You can add Distinct() after OrderBy() if you want to confirm there are no duplicates.