Comparing two lists and removing each item that contains an entry from the other list

半世苍凉 提交于 2020-08-10 19:06:17

问题


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.xml
  • C:\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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!