gpt4 book ai didi

c# - 如何比较两个列表中的项目?

转载 作者:行者123 更新时间:2023-11-30 20:57:01 27 4
gpt4 key购买 nike

我遇到了一个我似乎无法解决的问题。我有两个相同类型的列表,我需要检查这些列表是否匹配。我遇到了关于注释掉的 for 循环和现在正在使用的 nest foreach 循环的问题。我不需要同时使用两者,一个是我试图解决这个问题。

我已经通过调试器运行它,发现两个列表都保存相同的数据,我假设(使用 VS2010 调试器)位于列表中的相同元素。然而,当它被循环遍历时,它在第一个元素处失败。

我从类似的问题中研究过这个,我对 LINQ 表达式不是很熟悉(我正在做笔记以在空闲时间研究它)。

private bool ListMatch(List<T> list1, List<T> list2) 
{
if (list1 == null && list2 == null)
{
return true;
}
if ((list1 == null) || (list2 == null))
{
return false;
}
if (list1.Count != list2.Count)
{
return false;
}
if( list1.Equals( list2 ) )
{
return true;
}

/*for (var idx = 0; idx < list1.Count; idx++)
{
if( list1[ idx ] != list2[ idx ] )
{
return false;
}
}*/

foreach( var x in list1 )
{
bool hasDuplicates = false;
foreach( var y in list2 )
{

if( x == y )
{
hasDuplicates = true;
break;
}
}

if( hasDuplicates )
{
return true;
}
return false;
}

return true;
}

最佳答案

您可以使用 Enumerable.SequenceEqual在您进行相等性的手动预检查之后:

private bool ListMatch(List<T> list1, List<T> list2) 
{
if (list1 == null && list2 == null)
return true;

if ((list1 == null) || (list2 == null))
return false;

if (list1.Count != list2.Count)
return false;

if(list1.Equals(list2))
return true;

return Enumerable.SequenceEqual(list1, list2);
}

关于c# - 如何比较两个列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17168414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com