Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, I have a string list containing folder names I want to skip in my program, the list is like the one shown below

C#
List<String> IgnoreFolders = new List<String>();
IgnoreFolders.Add("SYNC ISSUES");
IgnoreFolders.Add("TRASH");
IgnoreFolders.Add("JUNK");

In my program I want to check if a folder name that I'm processing is this list( or partially ) What I've got is this ( it works but I'm sure there's a cleaner way ) If the folder name is "SYNC ISSUES1" or "SYNC ISSUES2" etc I want to exclude them also so Contains on the List won't work

C#
bool IgnoreFolder(Folder folder)
{
    String FolderName = folder.Name.ToUpper();
    bool RetVal = false;
       
    foreach(String s in IgnoreFolders)
    {
      if (FolderName.StartsWith(s.ToUpper()))
      {
          RetVal = true;
          break;
      }
    }
    return RetVal;
}


Hope this makes sense.

What I have tried:

The code shown above Partial search in generic List using Linq
Posted
Updated 25-Mar-16 1:23am
v2

If your goal is take a list (in this case, of FileNames) and quickly determine which items (in this case, strings) can be excluded based on some criterion (in this case, a match in a set of strings), consider something like this:
C#
using System;
using System.Collections.Generic;
using System.Linq;

IgnoreFolders = new List<string>
{
    "SYNC ISSUES",
    "TRASH",
    "JUNK",
};

TestNames = new List<string>
{
    "SYNC ISSUES1",
    "SYNC ISSUES2",
    "sometrash", "trash more", "my trash is",
    "myJUNK", "junkYOUR", "JUNKJUNKJUNK",
    "good name 1", "june bug good name",
    "tras hot good name", "jun k tras h"
};

var FileNamesToIgnore = TestNames
    .Where(name => IgnoreFolders
        .Any(itm => name.ToUpper()
            .Contains(itm)));

var GoodToGoFileNames = TestNames.Except(FileNamesToIgnore);
You could easily wrap this code in a Function; for re-use, I'd suggest having a boolean flag in that function that determined whether letter-case should be ignored (as in the example, here).
 
Share this answer
 
Comments
pkfox 25-Mar-16 7:27am    
Nice one Bill thank you
C#
bool IgnoreFolder(Folder folder)
{
    String folderName = folder.Name.ToLower();

    return IgnoreFolders.Any(x => folderName.Contains(x.ToLower()));
}
 
Share this answer
 
v3
Comments
pkfox 25-Mar-16 7:25am    
I see you fixed the ToLower - thanks that'll do :-)
This would be the LINQified version:
C#
bool IgnoreFolder(Folder folder)
{
    String FolderName = folder.Name.ToUpper();

    return IgnoreFolders.Any(ign => FolderName.StartsWith(ign.ToUpper());
}
 
Share this answer
 
Comments
pkfox 25-Mar-16 7:26am    
Thanks very much

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900