windowsgm
windowsgm

Reputation: 1616

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;
}

Upvotes: 0

Views: 43

Answers (1)

rattrapper
rattrapper

Reputation: 431

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.

Upvotes: 1

Related Questions