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.
C# filter list with iteration. In the first example, we use a foreach loop to filter a list. var words = new List<string> { "sky", "rock", "forest", "new", "falcon", "jewelry" }; var filtered = new List<string>(); foreach (var word in words) { if (word. Length == 3) { filtered.
Filtering operators are those operators which are used to filter the data according to the user requirement from the given data source or from the given sequence. For example, in an employee record, we want to get the data of the employees whose age in 21.
public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.
LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.
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())));
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 fileList data set are contained within the filterList set.
As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With