Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

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

I have 2 List objects (simplified):

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..)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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())));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...