c# – 仅比较FilesNames而不是内容是我的解决方案正确吗?
我们正在传输大量的文档/图像,在实际将这些文档保存到sql server之前我想比较2个文件列表.
>我的filePaths列表(将是一个txtFile,其中包含一个文件路径列表.转换为hashset) public static HashSet<string> ToHashSet(this string rootDirectory) { const string searchPattern = "*.*"; string[] files = Directory.GetFiles(rootDirectory,searchPattern,SearchOption.AllDirectories); return new HashSet<string>(files); } 所以我将MyHashSet与TheyHashSet进行比较. 只是在这里有点偏执,只想仔细检查是否除了我认为它做的. Except =“给定2个散列集比较所有文件路径,如果在MyList中找不到其中的那些,则产生结果” 我写了一个小测试,证明除了找到差异. 这是比较大文件的正确和最佳方法吗? 虚拟ProofOfConcept class Program { static void Main(string[] args) { const string rootDirectory = @"C:Tests"; HashSet<string> myHashSet= CreateDummyHashSet(rootDirectory,10); HashSet<string> theirHashSet= CreateDummyHashSet(rootDirectory,12); IEnumerable<string> result = theirHashSet.Except(myHashSet); foreach (var file in result) { Console.WriteLine(file); } Console.Read(); } public static HashSet<string> CreateDummyHashSet(string rootDirectory,int numberOfFiles) { var dummyHashSet = new HashSet<string>(); const string extension = ".txt"; const string fileName = "File"; for (int i = 0; i < numberOfFiles; i++) { string fullfileName = string.Format("{0}{1}{2}",fileName,i,extension); string path = Path.Combine(rootDirectory,fullfileName); dummyHashSet.Add(path); } return dummyHashSet; } } 解决方法
您不是在比较大文件,而只是比较它们的名称. Hashset非常适合在集合上执行此操作. 我不建议使用sbrauen提出的建议 var result = theirHashSet.Where(x => !myHashSet.Contains(x)); 因为它必须对m个条目进行n次操作,n和m分别是其HashSet和myHashSet中的条目数. Hashset应该在这些操作中表现更好.实际上比ExceptWith更好的是,因为Except是IEnumerable的扩展方法,而ExceptWith是HashSet中的方法<>. 编辑: 不同之处在于Except返回一个新的IEnumerable集合,而ExceptWith将从其HasSet中删除相同的条目.另外,ExceptWith更快,因为它知道HashTable的内部,Except只是一种扩展方法. 这是引擎盖下的样子 除了 Set<TSource> set = new Set<TSource>(comparer); foreach (TSource tSource in second) { set.Add(tSource); } foreach (TSource tSource1 in first) { if (!set.Add(tSource1)) { continue; } yield return tSource1; } ExceptWith foreach (T t in other) { this.Remove(t); } 你可以立即看到差异. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |