Robin
Robin

Reputation: 521

LINQ: Compare names (string) of two lists and return List<object> instead of list<string>

I am comparing two lists to find the ones that are missing in one of them. I have found other articles about this, but I could not find any of them using property comparison, but returning 'the whole object'.

So far I have:

return xmlFilesProduction
                .Select(i => i.Name).ToList()
                .Except(xmlFilesRepository
                .Select(x => x.Path.Replace(gitFilePath, ""))).ToArray();

For the xmlFilesRepository I first need to manipulate the path, to get the filename.

So far, it works quite all right, however, I do not want to return a list with the names, but a list with the whole object (FileInfo). Else, I need to loop over the xmlFilesProduction again.

Is this possible? And am I approaching the code above correctly (regarding O(n*m) and various select statements in one LINQ query)?

Thanks in advance!

Upvotes: 1

Views: 353

Answers (1)

Donut
Donut

Reputation: 112825

Try something like this:

var repoFileNames = xmlFilesRepository
   .Select(x => x.Path.Replace(gitFilePath, string.Empty))
   .ToHashSet();

return xmlFilesProduction.Where(i => !repoFileNames.Contains(i.Name)).ToArray();

This will put all the filenames from your "repository" into a HashSet<string> using the ToHashSet() extension method. HashSet<T> is great for checking set membership in constant time. Then it's just a matter of using .Where() instead of .Except() to filter out "production files" whose Name is found in the repoFileNames set.

Upvotes: 2

Related Questions