如果它们的长度为 1,我需要帮助来连接数组中的两个或多个连续项目。
例如,我想改变这个:
string[] str = { "one", "two", "three","f","o","u","r" };
至 :
str = {"one","two","three","four"};
使用GroupAdjacent
扩展程序(例如此处列出的扩展程序),您可以执行以下操作:
string[] input = ...
string[] output = input.GroupAdjacent(item => item.Length == 1)
.SelectMany(group => group.Key
? new[] { string.Concat(group) }
: group.AsEnumerable())
.ToArray();
如果效率在这里是一个大问题,我建议滚动你自己的迭代器块或类似的。
像这样的东西应该工作:
private string[] GetCombined(string[] str)
{
var combined = new List<string>();
var temp = new StringBuilder();
foreach (var s in str)
{
if (s.Length > 1)
{
if (temp.Length > 0)
{
combined.Add(temp.ToString());
temp = new StringBuilder();
}
combined.Add(s);
}
else
{
temp.Append(s);
}
}
if (temp.Length > 0)
{
combined.Add(temp.ToString());
temp = new StringBuilder();
}
return combined.ToArray();
}
这是我的答案,用于 LINQPad :)
void Main()
{
string[] str = { "one", "two", "three","f","o","u","r","five" };
string[] newStr = Algorithm(str).ToArray();
newStr.Dump();
}
public static IEnumerable<string> Algorithm(string[] str)
{
string text = null;
foreach(var item in str)
{
if(item.Length > 1)
{
if(text != null)
{
yield return text;
text = null;
}
yield return item;
}
else
text += item;
}
if(text != null)
yield return text;
}
输出:
一二 三四五
_ _ _
我认为最简单和更有效的方法就是遍历数组:
string[] str = { "one", "two", "three", "f", "o", "u", "r" };
List<string> output = new List<string>();
StringBuilder builder = null;
bool merge = false;
foreach(string item in str)
{
if (item.Length == 1)
{
if (!merge)
{
merge = true;
builder = new StringBuilder();
}
builder.Append(item);
}
else
{
if (merge)
output.Add(merge.ToString());
merge = false;
output.Add(item);
}
}
if (merge)
output.Add(builder.ToString());
你可以这样做:
string[] str = { "one", "two", "three", "f", "o", "u", "r" };
var result = new List<string>();
int i = 0;
while (i < str.Length) {
if (str[i].Length == 1) {
var sb = new StringBuilder(str[i++]);
while (i < str.Length && str[i].Length == 1) {
sb.Append(str[i++]);
}
result.Add(sb.ToString());
} else {
result.Add(str[i++]);
}
}