问题
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