C
C#17mo ago
Poller

✅ Remove Foreach

Any idea how i could eliminate this foreach contraption here? I expect to have a lot of (a bit more complicated) expressions there and i want to keep in somewhot compact.
6 Replies
Tvde1
Tvde117mo ago
var d = str.Select(i => string.Join(string.Empty, i))
.ToList();
var d = str.Select(i => string.Join(string.Empty, i))
.ToList();
also next time, post $code instead of a screenshot :)
MODiX
MODiX17mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat If your code is too long, post it to: https://paste.mod.gg/
MODiX
MODiX17mo ago
Tvde1#0587
REPL Result: Success
var str = "ffaabbccdd".ToArray().Chunk(2);
var d = new List<string>();

foreach(var i in str)
{
d.Add(string.Join("", i));
}
Console.WriteLine(string.Join(", ", d));

var e = str.Select(x => string.Join(string.Empty, x)).ToList();

Console.WriteLine(string.Join(", ", e));
var str = "ffaabbccdd".ToArray().Chunk(2);
var d = new List<string>();

foreach(var i in str)
{
d.Add(string.Join("", i));
}
Console.WriteLine(string.Join(", ", d));

var e = str.Select(x => string.Join(string.Empty, x)).ToList();

Console.WriteLine(string.Join(", ", e));
Console Output
ff, aa, bb, cc, dd
ff, aa, bb, cc, dd
ff, aa, bb, cc, dd
ff, aa, bb, cc, dd
Compile: 695.601ms | Execution: 93.942ms | React with ❌ to remove this embed.
ero
ero17mo ago
what is e for there? just bad example i guess? ah, Chunk returns a char[][]... yeah just use new string(x) or string.Concat(x), not string.Join("", x)
Poller
Poller17mo ago
thank you for the solution. i totally missed that i got the collections in Select... stupid me
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts