【问题标题】:How to compare two lists and get unmatching items - without using LINQ [closed]如何比较两个列表并获得不匹配的项目 - 不使用 LINQ [关闭]
【发布时间】:2013-04-16 06:36:43
【问题描述】:

我正在使用 2 个列表,

List<string> localfiles = new List<string>();

List<string> remotefiles = new List<string>();

我需要在远程文件中找到本地文件中不存在的所有新项目。使用 LINQ 更容易,但我不能使用 Linq,因为我的应用程序在 .net 2.0 中。

【问题讨论】:

    标签: c# list


    【解决方案1】:
    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);
    

    Dictionary 更多 efficient 用于查找,然后 List 如果您有超过 3 个项目:

    【讨论】:

    • +1 只是为了解决他的问题比 OP 付出更多的努力。
    • 但是,构建字典会降低性能
    • @TGH 同意,另一个惩罚是在两个列表中查找每个项目。所以是的,性能将取决于集合大小
    【解决方案2】:
    var temp = new List<string>();
    foreach(var item in remoteFiles){
      if(localfiles.Contains(item) == false){
         temp.Add(item);
      }
    }
    

    //temp 现在包含 remoteFiles 中本地文件中不存在的所有项目

    【讨论】:

    • 取决于本地文件的大小,您“可能”通过首先从列表中创建字典来获得更高的性能,因此“查找”会快得多(即在列表中使用 .Contains 是比在字典中查找键慢).. 但是您会产生创建字典的额外开销.. 与所有内容一样.. '这取决于';-) ...(就像lazyberezovsky 建议的那样:-))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多