C#比较两个字符串数组

C# compare two string arrays

我有两个文件

"Database.txt" 包含以下名称:

  1. 鼠标
  2. 熊猫

"Slave.txt" 包含以下名称:


熊猫

我想比较 "Slave.txt" 与 "Database.txt" 并创建第三个文件:

2. Cat  
4. Panda  

(来自 Slave.txt 的猫和熊猫在 Database.txt 中找到)

我的代码:

static void Main(string[] args)
    {
        String directory = @"C:\Users\user\Desktop\";
        String[] linesA = File.ReadAllLines(Path.Combine(directory, "Database.txt"));
        String[] linesB = File.ReadAllLines(Path.Combine(directory, "Slave.txt"));
        IEnumerable<String> onlyB = linesB.Intersect(linesA);
        File.WriteAllLines(Path.Combine(directory, "Result.txt"), onlyB);
    }

仅适用于 Database.txt 结构,例如:



鼠标
熊猫

没有行号。 有什么想法代替 .Intersect 只找到字符串的一部分,而不是完整的字符串?

一个非常简单的方法是使用来自 Linq 的 Any。无论如何,它只是检查 B 中一行的任何部分是否包含在 A 的任何行中。

var onlyB = linesA.Where(a => linesB.Any(b => a.ToLower().Contains(b.ToLower())));

注意:已更新为显示 A 中的行而不是 B 中的行。

您可以像这样使用 Linq:

static void Main(string[] args)
    {
        String directory = @"C:\Users\user\Desktop\";
        String[] linesA = File.ReadAllLines(Path.Combine(directory, "Database.txt"));
        String[] linesB = File.ReadAllLines(Path.Combine(directory, "Slave.txt"));
        IEnumerable<String> onlyB = linesA.Where(x=>linesB.Contains(x.Substring(x.IndexOf(". "+1))));
        File.WriteAllLines(Path.Combine(directory, "Result.txt"), onlyB);
    }

下面是我写的测试方法:

private string[] Matcher()
{
    string[] file1 = { "1. Dog","2. Cat","3. Mouse","4. Panda","5. Bear" };
    string[] file2 = { "Cat", "Panda" };
    string[] file3 = file1.Where(d => {
        foreach(string matcher in file2)
        {
            if(Regex.Match(d, @"^\d+\.\s+"+matcher + "$").Length > 0)
            {
                return true;
            }
        }
        return false;
    }).ToArray<string>();            

    return file3;
}

我想您在 file1 上的记录之前有行号或项目号。这将尝试使用正则表达式匹配 for : 一个数字组合、一个点和所需的值,并且当它与列表中的一个元素匹配时,它将将该元素带到 file3 数组中。

当你只搜索 Cat.

时,它会丢弃 Sabre Cat