我有两个数组,例如:
int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};
如何确定两个集合是否包含相同的元素?
我有两个数组,例如:
int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};
如何确定两个集合是否包含相同的元素?
如果IEnumerable对象事先排序,你也可以使用SequenceEqual
。
int[] a1 = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] a2 = new[] { 9, 1, 4, 5, 2, 3, 6, 7, 8 };
bool equals = a1.OrderBy(a => a).SequenceEqual(a2.OrderBy(a => a));
通过使用LINQ,您可以以表达性强和高效的方式实现它:
var q = from a in ar1
join b in ar2 on a equals b
select a;
bool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length;
join
的。请参考https://dev59.com/CknSa4cB1Zd3GeqPQ8hz#1561820了解其行为细节。 - Sedat Kapanoglu这些值会一直是唯一的吗?如果是,那么在检查相等长度后如何处理:
var set = new HashSet<int>(array1);
bool allThere = array2.All(set.Contains);
使用扩展方法(在3.0中是新功能)。如果两个数组的交集长度等于它们的并集长度,则这两个数组相等。
bool equals = arrayA.Intersect(arrayB).Count() == arrayA.Union(arrayB).Count()
简洁明了。
var shared = arr1.Intersect(arr2);
bool equals = arr1.Length == arr2.Length && shared.Count() == arr1.Length;
Framework 4.0引入了IStructuralEquatable接口,它有助于比较数组或元组等类型:
class Program
{
static void Main()
{
int[] array1 = { 1, 2, 3 };
int[] array2 = { 1, 2, 3 };
IStructuralEquatable structuralEquator = array1;
Console.WriteLine(array1.Equals(array2)); // False
Console.WriteLine(structuralEquator.Equals(array2, EqualityComparer<int>.Default)); // True
// string arrays
string[] a1 = "a b c d e f g".Split();
string[] a2 = "A B C D E F G".Split();
IStructuralEquatable structuralEquator1 = a1;
bool areEqual = structuralEquator1.Equals(a2, StringComparer.InvariantCultureIgnoreCase);
Console.WriteLine("Arrays of strings are equal:"+ areEqual);
//tuples
var firstTuple = Tuple.Create(1, "aaaaa");
var secondTuple = Tuple.Create(1, "AAAAA");
IStructuralEquatable structuralEquator2 = firstTuple;
bool areTuplesEqual = structuralEquator2.Equals(secondTuple, StringComparer.InvariantCultureIgnoreCase);
Console.WriteLine("Are tuples equal:" + areTuplesEqual);
IStructuralComparable sc1 = firstTuple;
int comparisonResult = sc1.CompareTo(secondTuple, StringComparer.InvariantCultureIgnoreCase);
Console.WriteLine("Tuples comarison result:" + comparisonResult);//0
}
}
public static bool ValueEquals(Array array1, Array array2)
{
if( array1 == null && array2 == null )
{
return true;
}
if( (array1 == null) || (array2 == null) )
{
return false;
}
if( array1.Length != array2.Length )
{
return false;
}
if( array1.Equals(array2))
{
return true;
}
else
{
for (int Index = 0; Index < array1.Length; Index++)
{
if( !Equals(array1.GetValue(Index), array2.GetValue(Index)) )
{
return false;
}
}
}
return true;
}
这将检查每个数组是否按顺序包含相同的值。
int[] ar1 = { 1, 1, 5, 2, 4, 6, 4 };
int[] ar2 = { 1, 1, 5, 2, 4, 6, 4 };
var query = ar1.Where((b, i) => b == ar2[i]);
Assert.AreEqual(ar1.Length, query.Count());
我发现这里提供的解决方案非常干净,虽然对于某些人来说有点啰嗦。
最好的事情是它也适用于其他IEnumerables。