「C# 相交部分匹配」

3

大家下午好, 我想进行两个文件夹内容的比较,现在有一种方法能够实现,但我想知道是否存在更好的方式。以下是我的实现代码:

    static void Main(string[] args)
    {
        reportDiffs("C:\\similar\\a", "C:\\similar\\b");
        Console.WriteLine("--\nPress any key to quit");
        Console.ReadKey();
    }

    public static void reportDiffs(string sourcePath1, string sourcePath2)
    {
        string[] paths1 = Directory.GetFiles(sourcePath1);
        string[] paths2 = Directory.GetFiles(sourcePath2);
        string[] fileNames1 = getFileNames(paths1, sourcePath1);
        string[] fileNames2 = getFileNames(paths2, sourcePath2);
        IEnumerable<string> notIn2 = fileNames1.Except(fileNames2);
        IEnumerable<string> notIn1 = fileNames2.Except(fileNames1);
        IEnumerable<string> inBoth = fileNames1.Intersect(fileNames2);

        printOut("Files not in folder1: ", sourcePath2, notIn1);
        printOut("Files not in folder2: ", sourcePath1, notIn2);
        printOut("Files found in both: ", "", inBoth);
    }

    private static string[] getFileNames(string[] currentFiles, string currentPath)
    {
        string[] currentNames = new string[currentFiles.Length];
        int i;

        for (i = 0; i < currentNames.Length; i++)
        {
            currentNames[i] = currentFiles[i].Substring(currentPath.Length);
        }
        return currentNames;
    }

    private static void printOut(string headline, string currentPath, IEnumerable<string> fileNames)
    {
        Console.WriteLine(headline);
        foreach (var n in fileNames)
        {
            Console.WriteLine(currentPath + n);
        }
        Console.WriteLine("--");
    }

感觉好像我错过了什么,有一种现成的数组方法,像交集(Intersect)一样,可以直接传递路径1和路径2,而不是像文件名1和2步骤那样操作,但是,说实话,我找不到框架中类似的方法。

谢谢, Sam


1
你看过 HashSet 集合吗? - Indy9000
1个回答

1

1
哦,真巧妙,早该知道会有这样的东西可用。我一直在忙着寻找部分交集,甚至没有想到这一点。将其替换掉,它就能完美运行了。 - Sam2S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接