簡體   English   中英

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結構,例如:



老鼠
熊貓

沒有行號。 有一些想法。相交只找到部分字符串,而不是完整的字符串?

一個非常簡單的方法是使用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上的記錄之前有行號或項目號。 這將嘗試匹配:數字組合,點和帶有正則表達式的所需值,並且當它與列表中的元素匹配時,它將把該元素帶到file3數組中。

當您僅搜索Cat時,它將丟棄Saber Cat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM