【发布时间】:2016-10-31 17:07:01
【问题描述】:
我是 C# 的新手,无法检查两个字符串之间的差异,数字用空格分隔,并返回第二个字符串中缺少的数字。
// Initial String with numbers
string stringA = "503 504 505 506 507 508 503 504 505 506"
string stringB = "503 504 504 505 506 507 505 508 503 506 505 506 504"
// I them split them into arrays
string[] inputArrayA = stringA.Split();
string[] inputArrayB = stringB.Split();
// I change them to integers
int[] numbersA = Array.ConvertAll(inputArrayA, int.Parse);
int[] numbersB = Array.ConvertAll(inputArrayB, int.Parse);
// Change the int[] array's to Lists
var listN = new List<int>(numbersA);
var listM = new List<int>(numbersB);
// Compare the lists and put in an array the numbers that are missing from listN
var missinNumbers = listM.Except(listN).ToList();
// Print List contents
missinNumbers.ForEach(Console.WriteLine);
但这现在不起作用。 我尝试使用 HashSet 实现一个单独的方法。但由于某种原因,missinNumbers 始终为空。
public static IEnumerable<int> FindMissing(IEnumerable<int> mainList, IEnumerable<int> listToCompare)
{
// Compare lists and return values that aren't in mainList but are in listToCompare
HashSet<int> convertedToHash = new HashSet<int>(mainList);
convertedToHash.ExceptWith(listToCompare);
return convertedToHash;
}
我不确定我做错了什么。我浏览了在 C# 中比较两个数组时建议的所有可能解决方案,并尝试了使用 LINQ 和两个 for 循环的不同方法,但我都无法弄清楚。 感谢您的帮助。
编辑: 我的目标是打印与 stringB 相比 stringA 中缺少的数字。所以,如果我们对这两个数组进行排序,我们可以看到缺失的数字是: 504 505 506。
【问题讨论】:
-
您的初始代码到底有什么问题?
-
Except的工作方式与应有的完全一样——第二个列表中没有第一个列表中不存在的数字。有些只是出现更多次。你想要的输出是什么? -
您希望丢失的数字是什么?
-
Getting the “diff” between two arrays in C#?。此外,“不工作”是相当模糊的。提供错误、您预期会发生但没有发生的事情,和/或发生的事情您没有预料到。
-
提出问题时,您拥有的代码是正确的。没有丢失的数字,两组都包含数字 503、504、505、506、507 和 508。它们仅在数量和顺序上有所不同,但这不是您提出的问题,也不是您的代码检查的内容。如果您提供了您想要的输出,将会很有帮助。