Search code examples
c#fileinfodirectoryinfo

C# Comparing two lists (FileData)


I'm creating a program which is going through a folder structure. If something has changed, I want to write it into a list. My problem is that I don't know how to save the changes in the lstChanges when Comparing the two lists. What is the syntax for the if-statement? This is what I got for now:

public static void GoThroughFileSystem(DirectoryInfo x)
    {
        foreach (DirectoryInfo d in x.GetDirectories())
        {
            //Console.WriteLine("Folder: {0}", d.Name);
            GoThroughFileSystem(d);
        }

        foreach (FileInfo f in x.GetFiles())
        {
            lstNew.Add(new FileData { path = f.FullName, ChangingDate = f.LastWriteTime });
            if (!lstOld.Contains(new FileData { path = f.FullName, ChangingDate = f.LastWriteTime }))
            {
                lstChanges.Add(new FileData { path = f.FullName, ChangingDate = f.LastWriteTime });
            }

        }
    }

Solution

  • Assuming you have the List<FileInfo> of files from the last iteration in your lstOld, you can update your if statement to

    //using System.Linq;
    
    if (!lstOld.Any(old => old.Path == f.FullName && old.ChangingDate == f.LastWriteTime))
    

    List<>.Contains uses default quality comparer. So, creating a new FileInfo will not work, unless FileInfo implements IEquatable<T>.Equals() properly.