如何从 IEnumerable 中删除行

How to remove rows from IEnumerable

我正在将 CSV 文件加载到 IEnumerable 中。

  string[] fileNames = Directory.GetFiles(@"read\", "*.csv");
  for (int i = 0; i < fileNames.Length; i++)
  { 
       string file = @"read\" + Path.GetFileName(fileNames[i]);
       var lines   = from rawLine in File.ReadLines(file, Encoding.Default)
                     where !string.IsNullOrEmpty(rawLine) 
                     select rawLine;
  }

之后我使用数据,但现在有几个文件几乎是空的,只有“;;;;;;” (数量不等)写在那里。

如何在不更改 csv 文件中的任何内容的情况下,在使用这些行之前删除这些行?

您不能从可枚举中删除行 - https://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

而是尝试使用过滤后的数据创建一个新数组,或者在您提供的 where 子句上对其进行过滤,例如:

string[] fileNames = Directory.GetFiles(@"read\", "*.csv");
         for (int i = 0; i < fileNames.Length; i++)
            { string file = @"read\" + Path.GetFileName(fileNames[i]);
var lines = from rawLine in File.ReadLines(file, Encoding.Default) where !string.IsNullOrEmpty(rawLine) && rawLine != ";;;;;;" select rawLine;}

您不能从 IEnumerable 中删除任何内容(例如从 List<T> 中删除),但是您可以添加过滤器:

lines = lines.Where(l => !l.Trim().All(c => c == ';'));

这不会删除任何内容,但您不会再处理这些行。

有多种解法。

  1. 将可枚举转换为列表,然后从列表中删除。这个有点贵。

  2. 创建一个函数。 // 如果需要,您可以应用多个过滤器。

    public IEnumrable<string> GetData(ref IEnumrable<string> data)
    {
          return data.Where(c=> !String.Equals(c,"<<data that you want to filter>>");  
    }
    

如果每行 ; 个字符的数量是可变的,那么您的 "where" 条件应该是这样的:

where !string.IsNullOrEmpty(rawLine) && !string.IsNullOrEmpty(rawLine.Trim(';'))

rawLine.Trim(';') 将 return 删除所有 ; 个字符的字符串副本。如果这个新字符串为空,则意味着可以忽略这一行,因为它只包含 ; 个字符。

另一种读取 CSV 文件的方法是使用 TextFieldParser class。它有 CommentTokensDelimiters 这可能对你有帮助。

; 指定为 CommentTokens 可能会对您有所帮助。

Tutorial