C#比较两个字符串数组

标签 c# string-comparison

我有两个文件

“Database.txt”包含以下名称:

  1. 鼠标
  2. Pandas

“Slave.txt”包含以下名称:


Pandas

我想比较“Slave.txt”和“Database.txt”并创建第三个文件:

2. Cat  
4. Panda  

(Cat and Panda from Slave.txt find in Database.txt)

My code:

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 结构,例如:



鼠标
Pandas

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

最佳答案

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

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

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

关于C#比较两个字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793902/

相关文章:

c# - 在 XNA 中处理纹理加载和跨多个类访问的最佳方法?

c# - MSTest:如果 3 个断言之一有效,如何断言肯定?

algorithm - 比较两个名称以查看它们是否相似/相同的算法

python - Python 中区分大小写的字符串比较

c# - '正则表达式' VS 'String Comparison operators/functions'

c# - Azure:将控制台 application.exe.config(从 app.config 生成)复制到 Azure 包

c# - Outlook SMTPClient 服务器错误 5.3.4 5.2.0

c# - 如果设置了 Min Pool Size,池中连接的生命周期是多少?

c# - LINQ to SQL 中的字符串比较结果为 null

c - 检查C中的字符串是否相等并打印答案