比较List <string>并获得包括空值在内的差异

时间:2019-03-28 11:52:44

标签: c# c#-4.0

我正在尝试比较两个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"

如何更有效地 简单地

1 个答案:

答案 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

如果两者 ExpectedListActualList 都没有特殊的"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}"));