我正在尝试比较两个List<string>
。只是需要具有差异
List<string> ExpectedList = new List<string>() { "apple","orange","grapes","mango"};
List<string> ActualList = new List<string>() { "gova","orange","GRAP"};
CollectionAssert.AreEqual(ExpectedList, ActualList)
预期结果应为如下所示的字符串
"apple gova, grape GRAP, Mango empty"
如何更有效地 或简单地?
答案 0 :(得分:2)
您可以尝试 Linq 和string.Join
:
List<string> ExpectedList = new List<string>() { "apple", "orange", "grapes", "mango" };
List<string> ActualList = new List<string>() { "gova", "orange", "GRAP" };
string report = string.Join(", ", Enumerable
.Range(0, Math.Max(ExpectedList.Count, ActualList.Count))
.Select(i => new {
expected = i < ExpectedList.Count ? ExpectedList[i] : null,
actual = i < ActualList.Count ? ActualList[i] : null,
})
.Where(item => item.actual != item.expected)
.Select(item => $"{item.expected ?? "empty"} {item.actual ?? "empty"}"));
Console.Write(report);
结果:
apple gova, grapes GRAP, mango empty
如果两者 ExpectedList
和ActualList
都没有特殊的"empty"
字符串,则可以缩短report
:
string report = string.Join(", ", Enumerable
.Range(0, Math.Max(ExpectedList.Count, ActualList.Count))
.Select(i => new {
expected = i < ExpectedList.Count ? ExpectedList[i] : "empty",
actual = i < ActualList.Count ? ActualList[i] : "empty",
})
.Where(item => item.actual != item.expected)
.Select(item => $"{item.expected} {item.actual}"));