[英]Reading text from files, then storing and comparing them
我试图用C#创建一个程序,该程序从文本文件中读取文本行并将它们存储在列表中。 然后,我必须将每一行与另一个同样大的文本行(50行)进行比较,然后将差异显示在屏幕上吗? 有人可以帮忙吗? 将不胜感激。 到目前为止,我只能读取文件。
TextReader tr = new StreamReader("file1.txt");
for (var i = 0; i < 1; i++)
{
tr.ReadLine();
}
TextReader tra = new StreamReader("file2.txt");
for (var f = 0; f < 1; f++)
{
tra.ReadLine();
}
只有一个字符(一个文件中的测验答案,另一个文件中的答案键
var count = File.ReadLines("file1.txt")
.Zip(File.ReadLines("file2.txt"), (f1, f2) => f1 == f2)
.Count(b => b);
输入:file1.txt
a
a
c
d
输入:file2.txt
a
a
b
d
输出:
3
编辑@AlexeiLevenkov
var two = new[] { true, false }.Count();
var one = new[] { true, false }.Count(b => b);
您可以创建简单的类来保存必要的数据。 在此类中,我们存储每个文件中的行和Color
来指示是否相等。
public class LineComparer
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public Brush Color { get; set; }
}
在下一步中,您必须使用文件中的数据填充列表:
public List<LineComparer> _comparer = new List<LineComparer>();
public void ReadFiles()
{
TextReader tr1 = new StreamReader("file1.txt");
TextReader tr2 = new StreamReader("file2.txt");
string line1, line2 = null;
while ((line1 = tr1.ReadLine()) != null)
{
_comparer.Add(new LineComparer{ Line1 = line1 });
}
int index = 0;
while ((line2 = tr2.ReadLine()) != null)
{
if(index < _comparer.Count)
_comparer[index].Line2 = line2;
else
_comparer.Add(new LineComparer{ Line2 = line2 });
index++;
}
tr1.Close();
tr2.Close();
_comparer.ForEach(x => { if(x.Line1 != x.Line2) x.Color = new SolidColorBrush(Colors.Red); else x.Color = new SolidColorBrush(Colors.Green); });
}
要显示文件差异,可以将ListBox
与ItemTemplate
使用:
<ListBox ItemsSource="{Binding}"
Grid.IsSharedSizeScope="True"
>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Color}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" SharedSizeGroup="A" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" SharedSizeGroup="B" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Line1}"
TextWrapping="Wrap" />
<TextBlock Text="{Binding Line2}"
TextWrapping="Wrap"
Grid.Column="2"
/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
例:
“ file1.txt”:
First
Second
Third
Fourth
Fifth
Sixth
Seventh
“ file2.txt”:
First
second
Third
Fourth
Fifth
结果是:
这是示例解决方案(FileComparer.zip)。
List<string> testlist1 = new List<string>();
List<string> testlist2 = new List<string>();
//populate Lists
for (int i = 0; i < testlist1.Count; i++)
{
if (testlist2[i] == testlist1[i])
//do something
else
//do something else
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.