C# Linq 过滤器 List<string> 其中包含来自另一个 List<string> 的字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15879771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:16:43  来源:igfitidea点击:

Linq filter List<string> where it contains a string value from another List<string>

c#.netlinqlistfiltering

提问by Mark Johnson

I have 2 List objects (simplified):

我有 2 个 List 对象(简化):

var fileList = Directory.EnumerateFiles(baseSourceFolderStr, fileNameStartStr + "*", SearchOption.AllDirectories);

var filterList = new List<string>();
filterList.Add("ThisFolderName");
filterList.Add("ThatFolderName");

I want to filter the fileLst to return only files containing any of folder names from the filterList. (I hope that makes sense..)

我想过滤 fileLst 以仅返回包含来自 filterList 的任何文件夹名称的文件。(我希望这是有道理的..)

I have tried the following expression, but this always returns an empty list.

我尝试了以下表达式,但这总是返回一个空列表。

var filteredFileList = fileList.Where(fl => fl.Any(x => filterList.Contains(x.ToString())));

I can't seem to make sense of why I am getting nothing, clearly I am missing something, but I have no idea what.

我似乎无法理解为什么我什么也没得到,显然我错过了一些东西,但我不知道是什么。

[EDIT]

[编辑]

Ok, so it appears I should have been clearer in my question, I was trying to search for files in my fileList with a substring containing string values from my filterList. I have marked the answer below for those who are trying to do a similar thing.

好的,所以看起来我应该在我的问题中更清楚,我试图在我的 fileList 中搜索文件,其中包含来自我的 filterList 的字符串值的子字符串。我在下面为那些试图做类似事情的人标记了答案。

采纳答案by fixagon

its even easier:

它更容易:

fileList.Where(item => filterList.Contains(item))

in case you want to filter not for an exact match but for a "contains" you can use this expression:

如果您想过滤的不是完全匹配而是“包含”,您可以使用以下表达式:

var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));

回答by Jamie Keeling

Try the following:

请尝试以下操作:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet(See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileListdata set are contained within the filterListset.

当您遍历filteredFileSet(参见LINQ Execution)时,它将包含一组IEnumberable 值。这是基于 Where 运算符检查以确保fileList数据集中的项目包含在filterList集中。

As fileListis an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

由于fileList是一组IEnumerable 字符串值,您可以将“项目”值直接传递到 Contains 方法中。

回答by Akrem

you can do that

你可以这样做

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));