C#中如何判断2个集合中数据是否相同

2025年03月21日 21:49
有5个网友回答
网友(1):

用LINQ, a对b做差集,b对a做差集,两次的结果都是空集合则说明两个集合完全相同,这是最简单的办法,只要一句话就能搞定.类似这样:(手写,不一定正确)

a.Except(b).Count()==0&&b.Except(a).Count()==0

网友(2):

static void Main()
{
List lstOne = new List() { 1, 2, 3, 4, 5, 10, 32 };
List lstTwo = new List() { 1, 2, 2, 3, 4, 3, 4, 5, 6, 7 };
var equalValue = lstOne.Intersect(lstTwo);
foreach (var i in equalValue)
{
// 考虑多个相同值 List lstTwo = new List() { 1, 2, 2, 3, 4, 3, 4, 5, 6, 7 };
while (lstTwo.IndexOf(i) >= 0)
{
int index = lstTwo.IndexOf(i);
lstTwo[index] = lstTwo[index] + 100;
}
}

foreach (var item in lstTwo)
{
Console.WriteLine(item);
}

Console.ReadKey();
}

网友(3):

定义数组c,先用循环,找出b中与a相等的所有大的数的下标,记入数组c,然后,根据c中的下表,对b中相应的数进行修改

网友(4):

集合都有下标,通过下标循环比较

网友(5):

List lstA = new List() { 1, 2, 3, 4, 5, 10, 32 };
List lstB = new List() { 1, 2, 3, 4, 5, 6, 7 };
for(int i=0;i if(lstA.Contains(lstB[i])){
lstB[i]+=100;
}
}