搜索列表然后从中删除 C#
Searching a list and then removing from it C#
我有一个文件名列表,例如:
helloworld#123.xml
hi.xml
test#1.xml
thisguyrighthere.xml
我正在设计的程序将使用此列表 (newFileList) 与另一个列表 (existingFileList) 进行比较以查找重复项。当我 运行 程序时,它将使用二分法搜索现有文件列表(它们实际上是大列表)并在找到它们时从新文件列表中删除。在 newFileList 被裁剪后,它会将剩余的元素添加到 existingFileList 中。因此,如果我 运行 程序两次使用完全相同的 newFileList,则在此过程结束后,newFileList 应该为空。
我遇到的问题(代码如下所示)是第一个元素没有从 newFileList 中删除,而是被重复添加到 existingFileList 并生成包含这些行的文件(最后一行是重复次数取决于程序 运行):
helloworld#123.xml
hi.xml
test#1.xml
thisguyrighthere.xml
helloworld#123.xml
以下是相关的代码片段:
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,同时防止重复。如果有人能想到更好的方法(我已经尝试过几次,这似乎是迄今为止最快的),我愿意改变这一切的工作方式。任何帮助将不胜感激!
为什么不使用 linq?这是你想要的吗?
newFileList.RemoveAll(item => existingFileList.Contains(item));
我发现这行得通:
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);
}
}
我有一个文件名列表,例如:
helloworld#123.xml
hi.xml
test#1.xml
thisguyrighthere.xml
我正在设计的程序将使用此列表 (newFileList) 与另一个列表 (existingFileList) 进行比较以查找重复项。当我 运行 程序时,它将使用二分法搜索现有文件列表(它们实际上是大列表)并在找到它们时从新文件列表中删除。在 newFileList 被裁剪后,它会将剩余的元素添加到 existingFileList 中。因此,如果我 运行 程序两次使用完全相同的 newFileList,则在此过程结束后,newFileList 应该为空。
我遇到的问题(代码如下所示)是第一个元素没有从 newFileList 中删除,而是被重复添加到 existingFileList 并生成包含这些行的文件(最后一行是重复次数取决于程序 运行):
helloworld#123.xml
hi.xml
test#1.xml
thisguyrighthere.xml
helloworld#123.xml
以下是相关的代码片段:
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,同时防止重复。如果有人能想到更好的方法(我已经尝试过几次,这似乎是迄今为止最快的),我愿意改变这一切的工作方式。任何帮助将不胜感激!
为什么不使用 linq?这是你想要的吗?
newFileList.RemoveAll(item => existingFileList.Contains(item));
我发现这行得通:
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);
}
}