说我有以下网址列表:
Url 1: https://www.example.com/dummy-path1?<query-params-here>
Url 2: https://www.example.com/dummy-path2?<query-params-here>
Url 3: https://www.example.com/specific-path?<query-params-here>
Url 4: https://www.example.com/path1?<query-params-here>
Url 5: https://www.example.com/path2?<query-params-here>
Url 6: https://www.example.com/specific-path?<query-params-here>
Url 7: https://www.example.com/path1?<query-params-here>
Url 8: https://www.example.com/path2?<query-params-here>
...
我想采取一组元素,以便最终我会:
Group1:
Url 3: https://www.example.com/specific-path?<query-params-here>
Url 4: https://www.example.com/path1?<query-params-here>
Url 5: https://www.example.com/path2?<query-params-here>
Group2:
Url 6: https://www.example.com/specific-path?<query-params-here>
Url 7: https://www.example.com/path1?<query-params-here>
Url 8: https://www.example.com/path2?<query-params-here>
注意:两个组没有必要具有相同数量的项目。
我尝试了SkipWhile
和TakeWhile
的几个LINQ组合:
var a = lines.SkipWhile(s => !s.Contains("example.com/specific-path"));
但是当我尝试应用TakeWhile(s => s.Contains("example.com/specific-path"))
时,它会失败,因为第一个元素(SkipWhile
之后)已经包含specific-path
。
如何使用LINQ实现此目的?
答案 0 :(得分:2)
可以使用MoreLinq.Segment:
完成此操作navigated.Segment(x => x.StartsWith("https://www.example.com/specific-path"));
var source = @"Url 1: https://www.example.com/dummy-path1?<query-params-here>
Url 2: https://www.example.com/dummy-path2?<query-params-here>
Url 3: https://www.example.com/specific-path?<query-params-here>
Url 4: https://www.example.com/path1?<query-params-here>
Url 5: https://www.example.com/path2?<query-params-here>
Url 6: https://www.example.com/specific-path?<query-params-here>
Url 7: https://www.example.com/path1?<query-params-here>
Url 8: https://www.example.com/path2?<query-params-here>";
var navigated = Regex.Matches(source, "https.+")
.Cast<Match>()
.Select(x => x.Value);
navigated
.Segment(x => x.StartsWith("https://www.example.com/specific-path"))
.Where(x => x.First().StartsWith("https://www.example.com/specific-path")) // skip first group that contains dummy path
.Dump();
结果: