Reputation: 53
I wonder if there is any way to save only the longest string from a list where a string has been extended.
The strings is paths from a register with users. Where the registerlevelis displayed as follow 1.2.3.4 or 1.6.3 and so on. The path is always seperated with "."
Min of path is two levels (example 1.2) but there is no max of number of levels.
When i loop through the register and found the specific user i add it to a list on the user. When the loop is done i need to remove all except the longest string where the subparts is exactly the same.
This is for a program that will export specific information from a register to Excel.
The program is a console application that will run automatically every night. This means that it is more important that it delivers accurate information than it is efficient in time.
var list = new List<string>();
list.Add("1.2.3.4");
list.Add("2.1.4");
list.Add("1.2.3");
list.Add("2.1.4.6");
list.Add("1.3.3");
list.Add("1.3.3.5");
LINQ for "itemsToRemove" just below is just one example to show what the idea of the functionality is.
var itemsToRemove = list.Where(x => list.Any(y => x.Contains(x))).ToList();
list.RemoveRange(itemsToRemove);
foreach(var item in list)
{
Console.WriteLine(item)
}
and the result should be as followed:
1.2.3.4
2.1.4.6
1.3.3.5
It means that items below is removed from the list cause there is longer paths that includes the item in the list:
1.2.3
2.1.4
1.3.3
Upvotes: 1
Views: 66
Reputation: 3018
You can use following query
var longestPaths = list
.Where(s => !list.Any(s2 => s2 != s && s2.IndexOf(s) == 0))
.ToList();
Upvotes: 2