如何比较多个文本文件(比如说7个)内容并将常用内容存储在另一个文本文件中 [英] How can I compare multiple text files (let's say 7) content and store common content in another textfile

查看:122
本文介绍了如何比较多个文本文件(比如说7个)内容并将常用内容存储在另一个文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个文本文件,他们有内容!我需要获取所有内容并进行比较,所以我尝试阅读并将它们存储在列表中,因为每个文本文件上下文都是列表索引

比如

1.txt在[0]和下一个2.txt在[1]等等......

但我不能比较那些......请可以任意一个帮助我!



示例:1.txt的值为1 2 3 4

2.txt的值为3 5 6
我应该得到输出为3即两个文件中的共同上下文类似如果我有许多文件的常见内容全部



我有什么尝试过:



我尝试使用列表,其中所有文本文件都存储在索引中但我无法比较那些!我是初学者并且学习c#

I have a multiple text files and they have content!I need to get all contents and compare them,So I tried reading and storing them in list as each text file context as index of list
like
1.txt in [0] and next 2.txt in [1] and so on...
but i cant compare those... Please Can any one help me!

example :1.txt has values 1 2 3 4
2.txt has values 3 5 6
I should get output as 3 i.e common context in both files similarly if I have many files common content of those all

What I have tried:

I tried using list where all text files are stored in index but i can't compare those!I am beginner and learning c#

推荐答案

如果你想到它并且逐步进行,这并不复杂。

将每个文件读成一个字符串:

This isn't complex if you think about it and take is stage by stage.
Read each file into a string:
string data = File.ReadAllText(pathToFile);



将其分成若干段进行比较:


Break that into individual segments to compare:

string[] bits = data.Split(' ', '\n');



如果你将这些中的每一个添加到集合中,以后可以使用循环来比较它们:


If you add each of these to a collection, you can later use a loop to compare them:

List<string[]> toCompare = new List<string[]>();
...
toCompare.Add(bits);



循环非常简单:


And the loop is pretty simple:

string[] soFar = toCompare[0];
for (int i = 1; i < toCompare.Count; i++)
    {
    soFar = soFar.Intersect(toCompare[i]).ToArray();
    if (soFar.Count() == 0) break;
    }

Linq Intersect方法返回两个集合中的所有常用值。

The Linq Intersect method returns all the common values in the two collections.


这篇关于如何比较多个文本文件(比如说7个)内容并将常用内容存储在另一个文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆