问题
I'm trying to essentially copy any list items in fileManifest but only those that don't contain in any of the items from exclusionFilters to a newly initialized list.
I haven't figured out an elegant way to do this other than a nested foreach loop.
Does someone by chance have a better solution for this problem? Maybe LINQ?
var fileManifest = new List<string>()
{
@"C:\Test\Directory1\File1.xml",
@"C:\Test\Directory1\File2.xml",
@"C:\Test\Directory1\Directory2\File1.xml",
};
var exclusionFilters = new List<string>()
{
@"Directory2\"
};
var filteredList = new List<string>();
Expected Output of filteredList:
C:\Test\Directory1\File1.xmlC:\Test\Directory1\File2.xml
回答1:
var filteredList = fileManifest.Where(x => exclusionFilters.All(y => !x.Contains(y))).ToList();
Description:
- Enumerable.Where Method: Filters a sequence of values based on a predicate.
- Enumerable.All Method: Determines whether all elements of a sequence satisfy a condition.
- String.Contains(String) Method: Returns a value indicating whether a specified substring occurs within this string.
- Enumerable.ToList Method: Creates a List from an IEnumerable.
来源:https://stackoverflow.com/questions/62831519/comparing-two-lists-and-removing-each-item-that-contains-an-entry-from-the-other