如何在服务器路径名字符串列表中查找重复项

How to find duplicates in a list of strings of server path names

I am trying to find duplicates in a list of strings of path names to the server: My paths will look like \UTIR\STORAGE-23-2015\DEPOSITS3_DEPOSIT_10-23-2015_1.pdf I will have have to 50 of these that I need to check the end of the path 3_DEPOSIT_10-23-2015_1.pdf to make sure there are no duplicates.

List<string> manypaths = (List<string>)TempData["temp"];
        var list= new List<string>();
        foreach (var item in manypaths)
        {
            if(list.Contains(item))
            {
                
            }
            else
            {
                list.Add(item);
            }
        }

我正在使用 dotnetzip 库,我已经尝试了 ContainsEntry、Contains。以及我在网上找到的所有其他内容。当我将这些文件添加到 zip 文件时,出现错误:

System.ArgumentException: 'An item with the same key has already been added.

using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
        {
            
            zip.AddFiles(list, @"\");

             
            MemoryStream output = new MemoryStream();

            zip.Save(output);
            return File(output.ToArray(), "application/zip");

        }

您可以使用 LINQ 轻松完成此操作。

manyPaths
  //.Select(x => x.Split(new char[] { '\' }).Last()) // drop this
  .Select(x => x.ToLower())
  .Distinct()
  .ToList()

这将确保列表没有重复项。如果您仍然遇到错误,则可能是其他原因。

编辑

如果您需要删除重复的文件名,但保留完整路径。您将丢失文件,或者必须重命名它们(例如 file.txt、1file.txt、2file.txt 等)

var fileGroups = manyPaths
        .Select(x => new { Path = x, Name = x.Split(new char[] { '\' }).Last().ToLower() })
        .GroupBy(x => x.Name)
        .ToList();


//TODO: init your zip

foreach(var group in fileGroups)
{
    int count = 0;

    foreach(var file in group)
    {
        var newName = count > 0 ? count + group.Key : group.Key;
        //TODO: save your file to zip
        count++;
    }
}

要通过最后一部分获得不同的路径,您可以使用 group by 最后一部分并取第一个元素,如以下代码:

List<string> distinctFiles = files
    .GroupBy(x => x.Split(new char[] { '\' }).Last())
    .Select(x => x.First())
    .ToList();

List<string> distinctFiles = files
    .GroupBy(x => Path.GetFileName(x))
    .Select(x => x.First())
    .ToList();

测试:

List<string> files = new List<string>
{
    @"\UTIR\STORAGE-23-2015\DEPOSITS3_DEPOSIT_10-23-2015_1.pdf",
    @"\UTIR\STORAGE1-23-2015\DEPOSITS3_DEPOSIT_10-23-2015_1.pdf",
    @"\UTIR\STORAGE-23-2015\DEPOSITS3_DEPOSIT_10-23-2015_11.pdf",
};

请注意,第一个和第二个是重复的,在不同的路径中

结果

"\UTIR\STORAGE-23-2015\DEPOSITS3_DEPOSIT_10-23-2015_1.pdf"
"\UTIR\STORAGE-23-2015\DEPOSITS3_DEPOSIT_10-23-2015_11.pdf"

希望对您有所帮助。