Jev*_*man 2 c# string list concatenation
我的问题是,如果我有一个如下所示的列表,
var list = new List<string>();
list.Add("12345");
list.Add("Words");
list.Add("Are");
list.Add("Here");
list.Add("13264");
list.Add("More");
list.Add("Words");
list.Add("15654");
list.Add("Extra");
list.Add("Words");
Run Code Online (Sandbox Code Playgroud)
我希望能够从列表中删除所有以数字开头的字符串,并将它们之间的字符串连接起来,如下所示,
单词在这里
更多单词
额外单词
这个逻辑看起来怎么样?以下是我一直在尝试做的事情,但我无法首先了解如何删除带有数字的字符串,更不用说在删除带有数字的字符串时创建换行符了。
foreach (string s in list)
{
if (s.StartsWith("1"))
s.Remove(0, s.Length);
else
String.Concat(s);
}
foreach (string p in list)
Console.WriteLine(p);
Run Code Online (Sandbox Code Playgroud)
您正在做的是对数据进行“分块”或“分页”,但是您需要逐一遍历每个源元素以确定页面的开始和停止位置。
public static IEnumerable<ICollection<T>> ChunkBy<T>(IEnumerable<T> source, Func<T, bool> predicate)
{
ICollection<T> currentChunk = new List<T>();
foreach (var item in source)
{
if (predicate(item))
{
if (currentChunk.Any())
{
yield return currentChunk;
currentChunk = new List<T>();
}
}
else
{
currentChunk.Add(item);
}
}
if (currentChunk.Any())
{
yield return currentChunk;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个可重用的方法(您可以添加this到第一个参数的开头以使其成为扩展方法),它利用IEnumerable和Yield-ing结果。本质上,您返回一个值流,其中每个值都是一个集合。所以它是一个列表的列表,但术语更加流畅。
这是做什么的
你可以这样调用这个方法:
var output = ChunkBy(list, x => char.IsNumber(x[0]))
.Select(ch => string.Join(" ", ch));
foreach (var o in output)
Console.WriteLine(o);
Run Code Online (Sandbox Code Playgroud)
这使
Words Are Here
More Words
Extra Words
Run Code Online (Sandbox Code Playgroud)