我已经能够创建一个查找特定文本文件的方法,并设法打印此文件中最大,最小和平均数字。
我使用了以下代码字符串;
var average = File.ReadAllLines(@"test.txt").Select(int.Parse).Average();
return average;
但是我没有找到任何方法可以查看文本文件并打印大于平均值的数字。如果有人给我一些有价值的指示,我会非常感激。 我的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//declare textfile
string textFile;
//read the textfile
StreamReader fromFile = new StreamReader(@"test.txt");
//calculate the result
int biggestNumber = readBiggest(fromFile);
int smallestNumber = readSmallest(fromFile);
double average = readAverage(fromFile);
//ask user to save the result in a textfile of his choice
Console.WriteLine("Files from test.txt has been gathered...");
textFile = userInput("Enter the filename that you wish to store the result in: ");
StreamWriter toFile = new StreamWriter(textFile);
//present the result
toFile.WriteLine("The greatest number is {0}, {1} is the smallest number. The average number is {2}", biggestNumber, smallestNumber, average);
toFile.Close();
}
private static double readAverage(StreamReader fromFile)
{
var average = File.ReadAllLines(@"test.txt").Select(int.Parse).Average();
return average;
}
private static int readBiggest(StreamReader fromFile)
{
var max = File.ReadAllLines(@"test.txt").Select(int.Parse).Max();
return max;
}
private static int readSmallest(StreamReader fromFile)
{
var min = File.ReadAllLines(@"test.txt").Select(int.Parse).Min();
return min;
}
private static string userInput(string nameOfTextFile)
{
Console.WriteLine(nameOfTextFile);
string answer = Console.ReadLine();
return answer;
}
}
}
答案 0 :(得分:2)
首先 - 不要读取文件3次。从磁盘上的文件中读取将是整个程序中最慢的部分,并且执行3次只会使3次更糟。阅读一次:
var numbers = File.ReadLines(@"test.txt").Select(int.Parse).ToList();
注意:如果您希望将该值用于多个类方法,只需将其分配给私有字段即可。
现在多次使用。
var average = numbers.Average();
var min = numbers.Min();
var max = numbers.Max();
获取数字>平均值,首先计算平均值,然后在Where
:
var greaterThanAverage = numbers.Where(x => x > average);
然后你可以迭代并打印出来:
foreach (var num in greaterThanAverage)
{
Console.Writeline(num.ToString());
}
答案 1 :(得分:0)
以下内容:
var data = File.ReadAllLines(@"test.txt").Select(int.Parse).ToList();
var avg = data.Average();
var gavg = data.Where(o=>o>avg).ToList();