本文介绍了VB.NET:检查列表项是否相等并且具有相同的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检测两个给定列表的项目是否相等?
How can I detect whether the items of two given lists are equal?
Dim list1 As New List(Of Integer)
list1.AddRange({1, 2, 3})
Dim list2 As New List(Of Integer)
list2.AddRange({3, 2, 1})
如果我使用 SequenceEqual
code> False ,因为项目的顺序不同。
If I compare them using SequenceEqual
I get False
because the order of the items is not the same. How can I compare them without sorting them first, though?
编辑:请注意,这应该尊重重复的,例如 {1,2,3,1}
与 {1,2,3}不一样
$ c> 1 在第一个列表中出现两次。)
Please take into account that this should respect duplicates, for example {1, 2, 3, 1}
is not the same as {1, 2, 3}
(item 1
occurs two times in the first list).
推荐答案
<System.Runtime.CompilerServices.Extension()> _
Function AreItemsEqual(Of T)(col1 As IEnumerable(Of T), col2 As IEnumerable(Of T)) As Boolean
' performance checks
If col1 Is col2 Then Return True
If col1 Is Nothing OrElse col2 Is Nothing Then Return False
If col1.Count <> col2.Count Then Return False
' compare their elements
Dim o1 As IEnumerable(Of T) = col1.OrderBy(Function(i) i)
Dim o2 As IEnumerable(Of T) = col2.OrderBy(Function(i) i)
Return o1.SequenceEqual(o2)
End Function
b $ b
用法:
Usage:
If list1.AreItemsEqual(list2) Then
...
这篇关于VB.NET:检查列表项是否相等并且具有相同的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!