找不到独特的单词

Dom*_*Dom 1 c# string-matching

谁能告诉我我的代码有什么问题?基本上,我只需要添加从唯一码字words1uniques列表中,以后我比较这两个words1words2.在if声明中,如果我删除!然后它找到匹配的单词(与我需要的相反)

    List<string> Unique(string lines1 ,string lines2,  char[] separators)
    {
        string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
        string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
        List<string> uniques = new List<string>();

        for (int i = 0; i < words1.Length; i++)
        {
            bool match;
            for (int x = 0; x < words2.Length; x++)
            {
                if (!words1[i].Equals(words2[x]))
                {
                    match = true;
                    uniques.Add(words1[i]);
                    break;
                }
                else
                {
                    match = false;
                }
            }
        }

        return uniques;
    }
Run Code Online (Sandbox Code Playgroud)

Anu*_*wan 5

您可以对循环进行微小的更改

    for (int i = 0; i < words1.Length; i++)
    {
        bool match=false;
        for (int x = 0; x < words2.Length; x++)
        {
            if (words1[i].Equals(words2[x]))
            {
                match = true;
                break;
            }

        }
        if(!match && uniques.Contains(words1[i]))
        { 
            uniques.Add(words1[i]);
        }
        { 
        uniques.Add(words1[i]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

为了使代码更短,您可以使用LINQ

List<string> Unique(string lines1 ,string lines2,  char[] separators)
{    
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return words1.Except(words2).ToList();
}
Run Code Online (Sandbox Code Playgroud)