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

Time:11-12

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

CodePudding user response:

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));
}
  • Related