C# 如何比较两个列表并获得不匹配的项-无需使用LINQ
我使用了两个列表C# 如何比较两个列表并获得不匹配的项-无需使用LINQ,c#,list,C#,List,我使用了两个列表 List<string> localfiles = new List<string>(); List<string> remotefiles = new List<string>(); List localfiles=new List(); List remotefiles=新列表(); 我需要在remotefiles中查找localfiles中不存在的所有新项目。使用LINQ更容易,但我不能使用LINQ,因为我的应用程序在
List<string> localfiles = new List<string>();
List<string> remotefiles = new List<string>();
List localfiles=new List();
List remotefiles=新列表();
我需要在remotefiles中查找localfiles中不存在的所有新项目。使用LINQ更容易,但我不能使用LINQ,因为我的应用程序在.net 2.0中。var temp=new List();
var temp = new List<string>();
foreach(var item in remoteFiles){
if(localfiles.Contains(item) == false){
temp.Add(item);
}
}
foreach(远程文件中的变量项){
if(localfiles.Contains(item)==false){
临时添加(项目);
}
}
//temp现在包含remoteFiles中不存在于localfiles中的所有项Dictionary files=new Dictionary();
Dictionary<string, bool> files = new Dictionary<string, bool>();
foreach (var file in localfiles)
if (!files.ContainsKey(file))
files.Add(file, false);
List<string> result = new List<string>();
foreach (var file in remotefiles)
if (!files.ContainsKey(file))
result.Add(file);
foreach(localfiles中的var文件)
如果(!files.ContainsKey(文件))
文件。添加(文件,false);
列表结果=新列表();
foreach(remotefiles中的var文件)
如果(!files.ContainsKey(文件))
结果.添加(文件);
Dictionary
更多用于查找,如果有3个以上的项,则列表
:
根据本地文件的大小,通过先从列表中创建字典,您“可能”会获得更高的性能,因此“查找”会快得多(即,在列表中使用.Contains比在字典中查找键慢得多)。。但是创建字典会增加额外的开销。。一切都是如此……”这取决于“;-)。。。(就像lazyberezovsky所建议的:-)
+1
只是为了解决他的问题花费了比OP更多的精力。但是,构建dictionary@TGH同意,另一个惩罚是查找两个列表中的每个项目。因此,性能将取决于集合大小