Home > Back-end >  LINQ way to check if a list contains an object from another list
LINQ way to check if a list contains an object from another list

Time:08-19

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

CodePudding user response:

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.

  • Related