2
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace FunkcjaSpilit
{
    class Program2
    {
        static int _MinWordLength = 7;

        static void Main()
        {
            DirectoryInfo filePaths = new DirectoryInfo(@"D:\project_IAD");
            FileInfo[] Files = filePaths.GetFiles("*.sgm");
            List<int> firstone = new List<int>();

            foreach (FileInfo file in Files)
            {
                int longWordsCount = CalculateLongWordsCount(file, _MinWordLength);
                string justFileName = file.Name;
                firstone.Add(longWordsCount);
                Console.WriteLine(("W pliku: " + justFileName) + " liczba długich słów to " + longWordsCount);
            }

            Console.WriteLine(firstone.Count);
            Console.ReadLine();
        }

        private static int CalculateLongWordsCount(FileInfo file, int _MinWordLength)
        {
            return File.ReadLines(file.FullName).
                Select(line => line.Split(' ').Count(word => word.Length > _MinWordLength)).Sum();
        }
    }
}

我在这一行的代码firstone.Add(longWordsCount);我想将长度超过 7 的所有单词添加到列表中,但是在运行此代码后,firstone.Add(longWordsCount);只添加目录中的文件总和(而不是长度超过 7 的所有单词的总和。 sgm 目录中的文件)。

我该如何解决?

预期成绩:

firstone.Add(longWordsCount);

应该将所有长度超过 7 的单词从目录中的所有文件中添加到列表中。

4

1 回答 1

3

您在该行中打印列表长度:

Console.WriteLine(firstone.Count);

它应该是:

Console.WriteLine(firstone.Sum(f => f));

编辑

但由于您根本没有真正使用该列表,我建议您将 foreach 替换为此,以避免保存未实际使用的列表。

int wordsWithTheRequiredLenghtCount = 0;
foreach (FileInfo file in Files)
{
    int longWordsCount = CalculateLongWordsCount(file, 7);
    wordsWithTheRequiredLenghtCount += longWordsCount;
    Console.WriteLine(("W pliku: " + file.Name) + " liczba długich słów to " + longWordsCount);
}

如果你真的不需要在文件字数前面打印文件名。并且只想要全局字数,@Dmitry Bychenko 解决方案要好得多。

但是他删除了它,所以我将在这里复制它,因为我发现它非常聪明。

var words = Directory
.EnumerateFiles(@"D:\project_IAD", "*.sgm")
  .SelectMany(file => File.ReadLines(file))
  .SelectMany(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
  .Where(word => word.Length > minWordLength))
  .Count();
于 2021-01-09T17:05:20.077 回答