繁体   English   中英

字符串列表-使用LINQ的部分条目StartsWith

[英]List of strings - partial entry StartsWith using LINQ

想象一下我有这段代码

public List<string> X

我加载以下项目:

launch.txt
reset.txt
文件夹名称
其他文件夹名称

我知道我可以通过调用X.Contains(“ value”)来查找该列表中是否有项目
但是如果我通过“ foldername / file.txt”,该怎么办。

检查字符串是否以X列表中的任何条目开头的最简单方法是什么? 理想情况下,我也想捕获“ foldername / ”和子目录中的所有文件,因此我想使用StartWith。

LINQ是正确的方法吗?

使用Enumerable.Any扩展方法,它返回true当且仅当存在其给定谓词返回序列中的一些项目true

string search = "foldername/file.txt";
bool result = X.Any(s => search.StartsWith(s));

当然, StartsWith可能实际上不适合您的方案。 如果X中只有一个名为foldername2的文件夹怎么办? 我怀疑,在这种情况下,您不希望resulttrue


如果要获取X中与搜索匹配的项目,可以执行以下操作。

string search = "foldername/file.txt";
IEnumerable<string> result = X.Where(s => search.StartsWith(s));

如果要获取X中与搜索匹配的第一项,则可以执行以下操作。

string search = "foldername/file.txt";
string result = X.FirstOrDefault(s => search.StartsWith(s));

如果您在摸索Path请使用Path类:

List<string> X = new List<string>(){
    "launch.txt","reset.txt","foldername","otherfoldername"    
};
string search = "foldername/file.tx";
var searchInfo = new
{
    FileNameWoe = Path.GetFileNameWithoutExtension(search),
    FileName = Path.GetFileName(search),
    Directory = Path.GetDirectoryName(search)
};

IEnumerable<String> matches = X.Select(x => new
{
    str = x,
    FileNameWoe = Path.GetFileNameWithoutExtension(x),
    FileName = Path.GetFileName(x),
    Directory = Path.GetDirectoryName(x)
}).Where(xInfo => searchInfo.FileName    == xInfo.FileNameWoe
               || searchInfo.FileNameWoe == xInfo.FileName
               || searchInfo.Directory   == xInfo.Directory
               || searchInfo.Directory   == xInfo.FileNameWoe
               || searchInfo.FileNameWoe == xInfo.Directory)
.Select(xInfo => xInfo.str)
.ToList();

查找: foldername因为文件名的FileNameWithoutExtension等于您要搜索的路径的目录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM