C# 比较字符串数组中的值

C# 比较字符串数组中的值,c#,string,compare,C#,String,Compare,我有一个字符串[],其中包含来自日志文件的错误消息。 现在我需要将它们相互比较,因为许多错误是相同的。 然后我需要返回它们,以便用正则表达式过滤整个日志文件 这是我的密码: foreach (string item in errSplit) { string[] lines = item.Split(new string[] {"\r\n", "\n"}, StringSplitOptions.None); fisrt = lines.FirstOrDefaul

我有一个字符串[],其中包含来自日志文件的错误消息。 现在我需要将它们相互比较,因为许多错误是相同的。 然后我需要返回它们,以便用正则表达式过滤整个日志文件

这是我的密码:

foreach (string item in errSplit)
{        
    string[] lines = item.Split(new string[] {"\r\n", "\n"}, StringSplitOptions.None);

    fisrt = lines.FirstOrDefault();

    // Here I woud like to loop thru the sring and compare the values
    // and save the string,so every error exists just onece
    fehler.WriteLine(fisrt);
}
这就是字符串的外观,知道吗:

Services.Exceptions.Exceptions-系统…
Services.Exceptions.Exceptions-系统…
Services.Exceptions.Exceptions-~/Default…


如果您只想创建一个只有一个给定条目的数组版本,那么有几种方法可以做到这一点。使用LINQ,这可能是最简单的:

IEnumerable<string> yourFilteredErrors = yourErrors.Distinct();

如果效率是一个问题,您应该将
列表
替换为
散列集

那么
可枚举。Distinct
呢?如果字符串项完全匹配,则只需返回
yourray.Distinct()
.ToArray()。如果您使用a而不是
string[]
它将自动为您解决问题。
List<string> filteredErrors = new List<string>();
foreach (string error in yourErrors) {
    if (!filteredErrors.Contains(error)) {
        filteredErrors.Add(error);
    }
}