从c#中的文件路径字符串列表中提取公共文件路径的最佳方法是什么?
例如:我在List变量中列出了5个文件路径,如下所示
c:\ abc\pqr\tmp\sample\b.txt
c:\ abc\pqr\tmp \new2\c1.txt
c:\ abc\pqr\tmp\b2.txt
c:\ abc\pqr\tmp\b3 .txt
c:\ abc\pqr\tmp\tmp2\b2.txt
输出应为c:\ abc\pqr\tmp
Geo*_*ett 16
因为使用LINQ*可以最好地解决所有问题:
*并非所有内容都能通过LINQ解决.
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<string> Files = new List<string>()
{
@"c:\abc\pqr\tmp\sample\b.txt",
@"c:\abc\pqr\tmp\new2\c1.txt",
@"c:\abc\pqr\tmp\b2.txt",
@"c:\abc\pqr\tmp\b3.txt",
@"c:\a.txt"
};
var MatchingChars =
from len in Enumerable.Range(0, Files.Min(s => s.Length)).Reverse()
let possibleMatch = Files.First().Substring(0, len)
where Files.All(f => f.StartsWith(possibleMatch))
select possibleMatch;
var LongestDir = Path.GetDirectoryName(MatchingChars.First());
}
}
Run Code Online (Sandbox Code Playgroud)
第一行获取要评估的可能匹配长度的列表.我们首先想要最长的可能性(因此我将枚举反转为0,1,2,3;将其转换为3,2,1,0).
然后我得到匹配的字符串,这只是给定长度的第一个条目的子字符串.
然后我过滤结果,以确保我们只包含所有文件开头的可能匹配.
最后,我返回第一个结果,它将是最长的子字符串并调用path.getdirectoryname,以确保文件名中有一些相同的字母,但不包括在内.
| 归档时间: |
|
| 查看次数: |
4135 次 |
| 最近记录: |