【问题标题】:Compare values in string array比较字符串数组中的值
【发布时间】:2014-11-17 20:05:57
【问题描述】:

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

这是我的代码:

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...

【问题讨论】:

  • Enumerable.Distinct 怎么样?如果 string 项完全匹配,则返回 yourArray.Distinct() .ToArray()
  • 如果您使用HashSet<T> 而不是string[],它将自动为您解决问题。

标签: c# string compare


【解决方案1】:

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

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

如果您需要数组而不是 IEnumerable,只需在 yourFilteredErrors 上调用 .ToArray()

或者,如果你不能使用 LINQ,你可以迭代:

List<string> filteredErrors = new List<string>();
foreach (string error in yourErrors) {
    if (!filteredErrors.Contains(error)) {
        filteredErrors.Add(error);
    }
}

如果关注效率,您应该将List&lt;string&gt; 替换为HashSet&lt;string&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多