什么是比较C#2的整数列表/阵列的最佳方式 [英] What is the best way to compare 2 integer lists / array in C#

查看:173
本文介绍了什么是比较C#2的整数列表/阵列的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较平等2的整数列表。我很高兴,如果这使得它更容易给他们提前进行排序。下面是我想比较两个事物的例子。对于下面,我希望结果是真实的。

请注意:永远不会有列表中的任何重复(非重复值)

 列表< INT>名单=新名单,LT; INT>(){1,4,6,7};
 INT [] myArray的=新INT [] {1,6,7,4};


解决方案

比较列表时是什么平等对你意味着什么?你关心的名单​​是完全一样的....按相同的顺序相同的项目?或者只是包含相同的价值观,不分顺序。

如果你真的想验证列表包含以相同的顺序,你可以使用 SequenceEqual()方法在LINQ值相同的序列:

 布尔areEqual = listA.SequenceEqual(数组listB);

如果该列表是不以相同的顺序,可以先对它们进行排序:

 布尔areEqual = listA.OrderBy(X => X).SequenceEqual(listB.OrderBy(X => X));

如果列表可以包含重复,而重复并不重要(相对于平等的),你可以使用一套比较:

 布尔setEqual =新的HashSet< INT>(为listA).SetEquals(数组listB);

如果重复没有关系,你是有意避开比较费用(订货,建筑HashSet的,等等),你可以先只比较两个集合的大小,只有当他们是比较一样的。

I want to compare 2 integer list for equality. I am happy to sort them in advance if that makes it easier. Here is an example of two things that i want to compare. For the below, i want the result to be true.

NOTE: there will never be any duplicates in the list (no repeating values)

 List<int> list = new List<int>(){1, 4,6,7};
 int[] myArray = new int[]{1, 6,7 ,4};

解决方案

What does equality mean to you when comparing lists? Do you care that the lists are exactly the same .... the same items in the same order? Or just contain the same set of values, regardless of order.

If you actually want to verify that the lists contain the same sequence of values in the same order, you can use the SequenceEqual() method in LINQ:

bool areEqual = listA.SequenceEqual( listB );

If the lists are not in the same order, you can first sort them:

bool areEqual = listA.OrderBy(x=>x).SequenceEqual( listB.OrderBy(x=>x) );

If the lists can contain duplicates, and the duplicates don't matter (with respect to equality), you can use set comparison:

bool setEqual = new HashSet<int>( listA ).SetEquals( listB );

If duplicates don't matter and you're interested in avoiding the expense of the comparison (ordering, building a hashset, etc), you could first just compare the sizes of the two collections, and only compare if they are the same.

这篇关于什么是比较C#2的整数列表/阵列的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆