如何在C#中的文件路径列表中提取常见的文件路径 [英] how to extract common file path from list of file paths in c#
问题描述
什么是最好的方式,从文件的路径字符串在C#中的列表中提取的共同文件路径
What is the best way extract the common file path from the list of file path strings in c#?
例如:
我有一个列表5档在List变量路径,如下图所示。
Eg: I have a list 5 file paths in List variable, like below
C:\abc\pqr\tmp\sample\b.txt结果
C:\\ \\abc\pqr\tmp\\\
ew2\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\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
output should be c:\abc\pqr\tmp
推荐答案
由于一切都是最好的解决LINQ *:
*不是一切都用最好的解决LINQ
Because everything is best solved with LINQ*:
*not everything is best solved with 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());
}
}
解释
的第一行得到可能的匹配的长度来评价的列表。我们首先要最长的可能(让我扭转这将是枚举0,1,2,3,把它变成3,2,1,0)。
Explanation:
The first line gets a list of lengths of possible matches to evaluate. We want the longest possibility first (so i reverse the enumeration which would be 0, 1, 2, 3; turning it into 3, 2, 1, 0).
然后我得到的字符串匹配,这简直是给定长度的第一项的子串。
I then get the string to match, which is simply a substring of the first entry of the given length.
然后我对结果进行筛选,以确保我们只包括可能的匹配所有文件开始。
I then filter the results, to ensure we only include possible matches that all files start with.
最后,我返回的第一个结果,这将是最长的子串并调用path.getdirectoryname保证,如果事情有一些相同的信件文件名它不包括
Finally, i return the first result, which will be the longest substring and call path.getdirectoryname to ensure if something has a few identical letters in the filenames it isn't included.
这篇关于如何在C#中的文件路径列表中提取常见的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!