搜索文件,多次出现

时间:2016-04-18 13:03:21

标签: c#

代码我只显示搜索字符串的第一次出现,我想显示每次出现,有谁知道我怎么做?

static void Main(string[] args)
 {
string yearInput ; // User input
// User input

string[] Year = System.IO.File.ReadAllLines(@"C:\Year.txt");
    string[] Month = System.IO.File.ReadAllLines(@"C:\Month.txt");
    string[] Rain = System.IO.File.ReadAllLines(@"C:\WS1_Rain.txt");


Console.Write("Enter a Year: ");
    yearInput = Console.ReadLine();

var yearIndex = Array.FindIndex(Year, year => year == yearInput);


var outputMonth = Month[yearIndex];// The corresponding Month for the input
var outputRain = Rain[yearIndex]; // The corresponding rain for the input


Console.WriteLine("Year:{0}    Month:{1}       Rain:{2}     ",yearInput ,outputMonth, outputRain );

     }

     }

3 个答案:

答案 0 :(得分:3)

您可以使用LINQ' Enumerable.Where进行过滤,Enumerable.Zip按索引加入所有内容:

var years = System.IO.File.ReadLines(@"C:\Users\Josef\Documents\Weather Data\Year.txt");
var months = System.IO.File.ReadLines(@"C:\Users\Josef\Documents\Weather Data\Month.txt");
var rains = System.IO.File.ReadLines(@"C:\Users\Josef\Documents\Weather Data\WS1_Rain.txt");

var yearMonthRainInfos = years
    .Zip(months, (y, m) => new { year = y, month = m })
    .Zip(rains, (x, r) => new { x.year, x.month, rain = r })
    .Where(x => x.year == yearInput);

foreach (var ymrInfo in yearMonthRainInfos)
{
    Console.WriteLine("Year:{0}    Month:{1}       Rain:{2}",
        ymrInfo.year, ymrInfo.month, ymrInfo.rain);
}

请注意,我已经使用ReadLines代替ReadAllLines,它不需要在开始处理之前将所有行读入内存。

如果您想"如果他们搜索的年份不存在于该文件中,则会显示一条消息" 最好将查询结果存储在集合,然后它必须只执行一次。因此,您可以使用ToListToArray

var yearMonthRainList = years
    .Zip(months, (y, m) => new { year = y, month = m })
    .Zip(rains, (x, r) => new { x.year, x.month, rain = r })
    .Where(x => x.year == yearInput)
    .ToList();
if (yearMonthRainList.Count == 0)  // or yearMonthRainList.Any()
{
    MessageBox.Show("The year " + yearInput + "was not found");
}
else
{
    foreach (var ymrInfo in yearMonthRainList)
    {
        Console.WriteLine("Year:{0}    Month:{1}       Rain:{2}",
            ymrInfo.year, ymrInfo.month, ymrInfo.rain);
    }
}

答案 1 :(得分:1)

您可以使用Linq获取所有索引

var matchingYearIndexes = Year.Select((y,i) => new { Year=y, Index=i})
                              .Where(x => x.Year == yearInput)
                              .Select(x => x.Index);

然后循环以获得相应的月份和降雨

foreach(ver index in matchingYearIndexes)
{
    Console.WriteLine(
        "Year:{0}    Month:{1}       Rain:{2}     ",
        yearInput,
        Month[index], 
        Rain[index]);
}

答案 2 :(得分:-1)

之后设置一个断点
var yearIndex = Array.FindIndex(Year, year => year == yearInput);

并检查yearIndex的值 如果这是一个整数,你应该得到1条记录。

如果那是一个整数数组,你需要循环