【问题标题】:Searching a list and then removing from it C#搜索列表,然后从中删除 C#
【发布时间】:2015-07-03 03:06:04
【问题描述】:

我有一个文件名列表,例如:

helloworld#123.xml
hi.xml
test#1.xml
thisguyrighthere.xml

我正在设计的程序将使用此列表(newFileList)与另一个列表(existingFileList)进行比较以查找重复项。当我运行该程序时,它将使用二进制搜索搜索现有文件列表(它们实际上是大列表),并在找到它们时从新文件列表中删除。修剪完 newFileList 后,它会将剩余的元素添加到现有的FileList。因此,如果我使用完全相同的 newFileList 运行程序两次,则在此过程结束后 newFileList 应该为空。

我遇到的问题(代码如下所示)是第一个元素没有从 newFileList 中删除,而是重复添加到 existingFileList 并生成包含这些行的文件(最后一行重复取决于关于程序运行了多少次):

helloworld#123.xml
hi.xml
test#1.xml
thisguyrighthere.xml
helloworld#123.xml

以下是相关代码sn-ps:

public class FileName : IComparable<FileName>
{
    public string fName { get; set; }
    public int CompareTo(FileName other)
    {
        return fName.CompareTo(other.fName);
    }
}

public static void CheckLists(List<FileName> newFileList, List<FileName> existingFileList)
    {
        for (int i = newFileList.Count - 1; i>-1; i--)
        {
            if (existingFileList.BinarySearch(newFileList[i]) > 0)
            {
                newFileList.Remove(newFileList[i]);
            }               
        }
    }

此过程的目的是从 FTP 获取文件列表并将它们复制到另一个 FTP,同时防止重复。如果有人能想到更好的方法(我已经尝试了几个,这似乎是迄今为止最快的),我愿意改变这一切的工作方式。任何帮助将不胜感激!

【问题讨论】:

  • 在这里查看最佳答案 - stackoverflow.com/questions/47752/… - 这就是你想要的吗?
  • 我现在无法测试代码,所以我可能会偏离目标(因此是 cmets),但在 CheckLists 循环中,我认为您需要复制 i 的值,然后在以下语句中使用副本。
  • 我需要能够遍历列表,HashSets 可以做到吗?
  • @Equalsk 如果你有机会告诉我你的意思,可以吗?我已经尝试按照你说的做,但没有成功。也许我只是不明白你在说什么。
  • 啊,我看你解决了。好东西。以防万一其他人好奇,我的意思是在你的循环中你应该把 int index = i 放在里面,然后你会用 newFileList[index] 代替。

标签: c# list binary-search


【解决方案1】:

为什么不使用 linq?这是你想要的吗?

newFileList.RemoveAll(item => existingFileList.Contains(item));

【讨论】:

  • 我找到了与您的第二个答案类似的解决方案。它需要是可迭代的。
【解决方案2】:

我发现这行得通:

public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
    {
        for (int i = targetFileList.Count - 1; i>-1; i--)
        {
            sourceFileList.RemoveAll(x => x.fName == targetFileList[i].fName);             
        }
    }

【讨论】:

  • 基本可以是1-liner sourceFileList.RemoveAll(x =&gt; targetFileList.Any(y =&gt; y.fName == x.fName));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多