Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Create a Func<string, bool> from an IEnumerable<string>

Greatings, everybody! I’m trying to create a Function that will be used for Filtering File Paths from a String Array by Name and Extension but I’m facing some dificulties. The thing is that I would like to Use an Alternative of Declaring a Function using a List of Names and Extensions. For example: IEnumerable<string> Specific_Extensions_List = {".txt", ".bin", ".dat"};

Func<string, bool> List_Filter_Y = Filter_Y =>
    Filter_Y.EndsWith(".bak") ||
    Filter_Y.EndsWith(".bin") ||
    Filter_Y.EndsWith(".dat"); // Here is Declared Directly, I don't want that

Here’s the Source Code:

/** <summary> Creates a File Names Filter from a Specific Names List. </summary>
<param name = "Specific_Names_List" > The List used for Creating the File Names Filter. </param>

<returns> The File Names Filter. </returns> */

private Func<string, bool> Create_FileNames_Filter(IEnumerable<string> Specific_Names_List)
{
int Specific_Names_Count = Specific_Names_List.Length;
Func<string, bool> File_Names_Filter;

for(int Index = 0; Index < Specific_Names_Count; Index++)
{
string Specific_Name = Specific_Names_List[Index];
Func Filters_Generator => Filters_Generator.StartsWith(Specific_Name);

File_Names_Filter = Filters_Generator;
}

return File_Names_Filter;
}

Once the Filtering Function (Fun<string, bool>) is Generated from the Specified Strings Collection (IEnumerable<string) with the Method from above, it will be used for Filtering the Strings (Access Paths) Stored in the Strings Array with the Following Expression:
IEnumerable<string> Filtered_List = Input_Files_List.Where(List_Filter);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This should do what you want:

private Func<string, bool> Create_FileNames_Filter(IEnumerable<string> Specific_Names_List)
{
  return y => Specific_Names_List.Any(ext => y.EndsWith(ext));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading