简体   繁体   中英

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

        }
    }

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.

You can also try old fashion left outer join :)

var lParent = x.GetFiles();
var lChild = lstOld;

var differences = lParent.GroupJoin(
    lChild,
    p => p.FullName,
    c => c.LastWriteTime,
    (p, g) => g
        .Select(c => new { FullName = p.FullName, LastWriteTime = c.LastWriteTime})
        .DefaultIfEmpty(new { FullName = p.FullName, LastWriteTime = null}))
    .SelectMany(g => g);

If your goal is to gather all unique values from both collections, the thing you need is called full outer join. For two identically typed collections you can just use union and remove common part:

lParent.Union(lChild).Except(lParent.Intersect(lChild));

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