简体   繁体   中英

List of Subpath strings Compared to List of FileInfo

I have the below method that is comparing a list (Rows) of subpaths to a List<FileInfo> , and adding any missing entries to a list _missingImageFolderEnteries . I'm using LINQ and have noticed it seems surprisingly slow to process. Any ideas why or thoughts on how to improve performance? Perhaps LINQ isn't right here but I thought it should be more efficient than standard looping.

private List<FileInfo> _imageFilesInFolderPathList = new List<FileInfo>();
private readonly List<Tuple<string, string>> _missingImageFolderEnteries = new List<Tuple<string, string>>();
private void CrossCheckImageWithFolder(EnumerableRowCollection<DataRow> Rows)
{
    foreach (var dr in Rows)
    {
        var filepath = dr[ImagePathHeader].ToString();

        if (!_imageFilesInFolderPathList.Any(row =>
            row.FullName.EndsWith(FilePathHandler.FormatSubPath(filepath))))
            _missingImageFolderEnteries.Add(
                new Tuple<string, string>(
                    filepath.Substring(CommonInitFolder.Length).StartsWith("\\")
                        ? filepath.Substring(CommonInitFolder.Length)
                        : "\\" + filepath.Substring(CommonInitFolder.Length),
                    " does not exist in image folder"));
    }

    _missingImageFolderEnteries.Sort((x, y) => y.Item1.CompareTo(x.Item1));
}

public static string FormatSubPath(string path, bool needsSlash = true)
{
    var returnPath = path;
    if (returnPath.StartsWith("."))
        returnPath = returnPath.Substring(1);
    if (!returnPath.StartsWith("\\") && needsSlash)
        returnPath = "\\" + returnPath;
    else if (returnPath.StartsWith("\\") && !needsSlash)
        returnPath = returnPath.Substring(1);

    return returnPath;
}

Linq is a level of abstraction so it could never be faster than manual loop.

As for your problem I would try converting _imageFilesInFolderPathList to HashSet<string> containing names of files. Also you will need to compare whole string insted of using EndsWith to get performance boost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM