How should I compare each element values in two lists?

左心房为你撑大大i 提交于 2019-12-19 12:22:13

问题


In my unit test method,

I am having two list. One is the expectedValueList and other is actualvalueList.

expectedValueList={a=1,b=2,c=3,d=4}

actualvalueList={d=4,b=2,c=3,a=1}

I am comparing only one element by doing this

CollectionAssert.AreEqual(expectedValueList.Select(x => x.a).ToList() ,actualvalueList.Select(x => x.a).ToList())

how to compare remaining elements ?


回答1:


You can use SequenceEqual if they are already in order directly

expectedValueList.SequenceEqual(actualvalueList);

if they are not in order than you can apply ordering as well before using sequence equal like

expectedValueList.OrderBy(x => x).SequenceEqual(actualvalueList.OrderBy(y => y));

Example

List<int> l1 = new List<int> { 1, 2, 3, 4 };
List<int> l2 = new List<int> { 3, 1, 2, 4 };

if (l1.OrderBy(x => x).SequenceEqual(l2.OrderBy(y => y)))
{
     Console.WriteLine("List are equal"); // will write this
}

if (l1.SequenceEqual(l2))
{
     Console.WriteLine("List are equal"); 
}
else
{    
     Console.WriteLine("List are not equal"); // will write this    
}



回答2:


I am expecting its a List<int> and not key-value pairs as you mentioned in comments. try something like this:

Assert.AreEqual(actualvalueList.Count(), expectedValueList.Count());
for(int i=0;i<actualvalueList.Count();i++)
{
   Assert.AreEqual(actualvalueList[i], expectedValueList[i]);
}

or

CollectionAssert.AreEqual(expectedValueList, actualvalueList);

Edit

if you don't want to compare one value, then remove from Lists:

actualvalueList.Remove(actualvalueList.Select(x => x.d).FirstOrDefault())


来源:https://stackoverflow.com/questions/18395555/how-should-i-compare-each-element-values-in-two-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!