Reputation: 839
I have a list of paths that look like //servername/d$/directory
I am getting the serverName from the path with the following
var host = somePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
I want to refine this list to only 1 server Name listed (say the first one found)
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
Upvotes: 1
Views: 35
Reputation: 37020
You can group them by the server name (by trimming the start and splitting on the /
character and taking the first item), and then select the first item from each group into a new list:
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();
From your first code example it's not clear if the paths begin with \
, so to handle both cases you can do:
var results = serverNames
.GroupBy(name => name.TrimStart('\\', '/', ' ').Split('\\', '/')[0])
.Select(group => group.First())
.ToList();
Upvotes: 4