使用linq在通用列表中进行部分搜索 [英] Partial search in generic list using linq
问题描述
大家好,我有一个字符串列表,其中包含我想在程序中跳过的文件夹名称,列表如下所示
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
List<String> IgnoreFolders = new List<String>();
IgnoreFolders.Add("SYNC ISSUES");
IgnoreFolders.Add("TRASH");
IgnoreFolders.Add("JUNK");
在我的程序中,我想检查我正在处理的文件夹名称是否是这个列表(或部分)我得到的是这个(它有效,但我确定有一个更清洁的方式)如果文件夹名称是SYNC ISSUES1或SYNC ISSUES2等我也想将它们排除在列表中的包含不起作用
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
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;
}
希望这是有道理的。
< b>我尝试了什么:
上面显示的代码使用Linq
Hope this makes sense.
What I have tried:
The code shown above Partial search in generic List using Linq
推荐答案
如果你的目标是获取一个列表(在这种情况下,是FileNames)并快速确定哪些项目(在这种情况下,字符串)可以根据某些标准排除(在这种情况下,一组中的匹配)字符串),考虑这样的事情:
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:
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);
您可以轻松地将此代码包装在一个函数中;为了重复使用,我建议在该函数中有一个布尔标志,用于确定是否应忽略letter-case(如示例中所示)。
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).
bool IgnoreFolder(Folder folder)
{
String folderName = folder.Name.ToLower();
return IgnoreFolders.Any(x => folderName.Contains(x.ToLower()));
}
这将是LINQified版本:
This would be the LINQified version:
bool IgnoreFolder(Folder folder)
{
String FolderName = folder.Name.ToUpper();
return IgnoreFolders.Any(ign => FolderName.StartsWith(ign.ToUpper());
}
这篇关于使用linq在通用列表中进行部分搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!