我有两个数组.例如:
int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};
确定它们是否具有相同元素的最佳方法是什么?
如果SequenceEqual
首先对IEnumerable对象进行排序,您也可以使用它.
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;
这些价值总是独一无二的吗?如果是这样,那么(检查等长后):
var set = new HashSet(array1); bool allThere = array2.All(set.Contains);
var shared = arr1.Intersect(arr2); bool equals = arr1.Length == arr2.Length && shared.Count() == arr1.Length;
使用扩展方法(3.0中的新增功能).如果两个数组的交集长度等于它们的Union的长度,那么数组是相等的.
bool equals = arrayA.Intersect(arrayB).Count() == arrayA.Union(arrayB).Count()
简洁.
对于最有效的方法(Reflectored来自微软的源代码),看到堆栈溢出问题在他们的项目顺序的平等,不论比较两个集合.
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.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 } }