【问题标题】:How to use Exists function in List<string>?如何在 List<string> 中使用 Exists 函数?
【发布时间】:2014-07-20 18:54:39
【问题描述】:

我的代码在这里:

string[] Lines = File.ReadAllLines(textBox1.Text);
            List<string> NewLines = new List<string>();
            foreach (string Line in Lines)
            {
                string newLine = Line.Trim();
                if (!NewLines.Exists(newLine))
                    NewLines.Add(newLine);

NewLines.Exists() 函数产生这个错误:

System.Collections.Generic.List&lt;string&gt;.Exists(System.Predicate&lt;string&gt;) 的最佳重载方法匹配有一些无效参数

【问题讨论】:

  • 我真的相信阅读 MSDN 文档应该足以回答此类问题......
  • 如果你的文件很大,我可以建议使用HashSet&lt;string&gt;吗?
  • 如果您将所有变量名驼峰化,代码的可读性会好得多。

标签: c# list


【解决方案1】:

如果您需要检查该行是否已存在于列表中,请使用Contains():

if (!NewLines.Contains(newLine))
      NewLines.Add(newLine);

Exists() 方法需要一个 Predicate&lt;string&gt;,您可以按如下方式使用它:

NewLines.Exists(x => x == newLine)

【讨论】:

  • Mer30,NewLines.Contains 是我的需要
猜你喜欢
  • 2020-06-06
  • 2017-02-25
  • 2020-10-20
  • 2014-03-29
  • 1970-01-01
  • 2016-09-10
  • 2020-02-23
  • 2022-01-05
  • 2012-02-08
相关资源
最近更新 更多