C
C#2y 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
Tvde12y 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
MODiX2y 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
MODiX2y 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
ero2y 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
PollerOP2y ago
thank you for the solution. i totally missed that i got the collections in Select... stupid me
Accord
Accord2y 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