我有一个看起来像的路径列表 //服务器名称/ d $ /目录
我正在使用以下命令从路径中获取serverName
var host = somePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
我想将此列表优化为仅列出1个服务器名称(例如找到的第一个服务器名称)
Example
if the list contains
//serverA/d$/directoryA
//serverA/d$/directoryB
//serverA/d$/directoryC
//serverB/d$/directoryD
//serverB/d$/directoryE
the list would turn into
//serverA/d$/directoryA
//serverB/d$/directoryD
答案 0 :(得分:4)
您可以按服务器名称对它们进行分组(修剪开始并在/
字符上分割并取第一项),然后从每个组中选择第一项进入新列表:
var serverNames = new List<string>
{
"//serverA/d$/directoryA",
"//serverA/d$/directoryB",
"//serverA/d$/directoryC",
"//serverB/d$/directoryD",
"//serverB/d$/directoryE",
};
var results = serverNames
.GroupBy(name => name.TrimStart('/').Split('/')[0])
.Select(group => group.First())
.ToList();
在您的第一个代码示例中,尚不清楚路径是否以\
开头,因此可以同时处理两种情况:
var results = serverNames
.GroupBy(name => name.TrimStart('\\', '/', ' ').Split('\\', '/')[0])
.Select(group => group.First())
.ToList();