Here I have a string list as follows:
List<string> str = new List<string>
{ "1", "22", "3", "44", "55", "666666", "7777777", "8", "99" };
What I want is merging short strings into a long string of length less than n.
Expect:
n = 5
newlist = { "1223", "4455", "666666", "7777777", "899" };
CodePudding user response:
void Main()
{
List<string> str = new() { "1", "22", "3", "44", "55", "666666", "7777777", "8", "99" };
const int n = 5;
List<string> newList = new();
var newString = string.Empty;
foreach (var s in str)
{
if ((newString.Length s.Length) <= n)
{
newString = s;
continue;
}
newList.Add(newString);
newString = s;
}
newList.Add(newString); // Don't forget the last under length string
Console.WriteLine(newList);
}
// Outputs "1223", "4455", "666666", "7777777", "899"
// Also handles empty input strings
CodePudding user response:
Late to the answer. LINQ .Aggregate()
is alternative solution for foreach
loop.
The .Aggregate()
is able to use to iterate with the current value and next value.
Check
toBeAppended
value.1.1 If
toBeAppended.Length
>n
, add thecurrent
value to theresult
. And you need to reset thecurrent
value.1.2 Else set the
current
withtoBeAppended
.After the end of the interaction, make sure you need to add the last value to the
result
.
List<string> str = new List<string> { "1", "22", "3", "44", "55", "666666", "7777777", "8", "99" };
int n = 5;
var result = new List<string>();
var last = str.Aggregate("",
(current, next) =>
{
var toBeAppended = current next;
if (toBeAppended.Length >= n)
{
result.Add(current);
current = next;
}
else
{
current = toBeAppended;
}
return current;
});
result.Add(last);