mharre
mharre

Reputation: 263

LINQ way to check if a list contains an object from another list

I have a List of objects and I want to check if a different List contains a certain object. I have written some code that works for it I just couldn't quite figure out a way to do it with LINQ (if possible)

                        foreach (var file in files)
                        {
                            if (!pushedList.Contains(file))
                            {
                                myStack.Push(file);
                                pushedList.Add(file);
                            }
                        }

Something like if (!pushedList.Contains(files.Select(f => f))) except I just want to select the 1 file that is inside of files. The two List's in question are files and pushedList

Upvotes: 0

Views: 1121

Answers (1)

NetMage
NetMage

Reputation: 26936

Since LINQ is for querying and not modifying, you just use it to figure out the files you need to process, then do the processing on those files:

var missingFiles = files.Where(f => !pushedList.Contains(f)).ToList();
myStack.PushRange(missingFiles);
pushedList.AddRange(missingFiles);

Depending on the sizes, it may be worthwhile to make a HashSet from pushedList before doing the query, or ideally, make pushedList a HashSet instead of a List.

This uses an extension to Stack<T>:

public static class StackExt {
    public static void PushRange<T>(this Stack<T> s, IEnumerable<T> Ts) {
        foreach (var t in Ts)
            s.Push(t);
    }
}

Upvotes: 1

Related Questions