C# 从文件中读取文本,然后存储和比较它们

C# 从文件中读取文本,然后存储和比较它们,c#,list,text-files,storage,C#,List,Text Files,Storage,我试图用C语言创建一个程序,从文本文件中读取文本行并将其存储在列表中。然后我必须将每一行与另一个同样大(50行)的文本文件进行比较,并将差异显示在屏幕上?有人能帮忙吗?我们将不胜感激。到目前为止,我只能阅读这些文件 TextReader tr = new StreamReader("file1.txt"); for (var i = 0; i < 1; i++) { tr.ReadLine(); } T

我试图用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();
        }
TextReader tr=newstreamreader(“file1.txt”);
对于(变量i=0;i<1;i++)
{
tr.ReadLine();
}
TextReader tra=新的StreamReader(“file2.txt”);
对于(var f=0;f<1;f++)
{
tra.ReadLine();
}
只有一个字符(测验答案在一个文件中,答案键在另一个文件上

输入:file1.txt

a
a
c
d
a
a
b
d
输入:file2.txt

a
a
c
d
a
a
b
d
输出:

三,


编辑@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); });
}
例如:

“file1.txt”:

“file2.txt”:

结果是:

是示例解决方案(FileComparer.zip)。

List testlist1=new List();
List testlist2=新列表();
//填充列表
for(int i=0;i
查找与文本之间的差异是一项非常困难的任务,并且高度依赖于上下文。您能否准确地确定要比较的内容类型(程序、数字等)?您可以将所有文件加载到两个单独的列表中,然后根据另一个列表的内容迭代该列表。这里有许多选项。如果您发布一个小片段,说明正在比较的数据的外观,以及您需要逐行进行的比较,或者您必须考虑到计算跨越多行的差异?对不起,伙计们。正在逐行比较提到的两个文件。每行上只有一个字符(测验答案在一个文件中,答案键在另一个文件中。我基本上创建了一个程序,使用另一个作为答案键的文件对测验进行评分。在这种情况下,我投票支持DJ KRAZE的解决方案:List@AlexeiLevenkov事实上,我需要lambda,请参见编辑并测试它。+1。我之前关于计数中不需要lambda的评论是错误的-t序列包含isMathing值,所以只需计算一次isMatching==true。您的答案不起作用,至少对于像我这样的色盲:)@I4V检查我的答案:)我添加了一个指向示例解决方案的链接。
First
Second
Third
Fourth
Fifth
Sixth
Seventh
First
second
Third
Fourth
Fifth
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
}