C
C#6mo ago
BenMcLean

Collections expression to add an item at the start.

I've got this:
public uint[] Palette => [.. (new List<uint> { 0u }), .. Colors.Take(255)];
public uint[] Palette => [.. (new List<uint> { 0u }), .. Colors.Take(255)];
What I intend for it to do is to return an array of uints which starts with zero as the first value, then appends the contents of Colors (another array of uint) up to a maximum of 255 items, so that this array can never be larger than 256 items. This expression I've got appears to work, technically, but it also appears that I should be able to do this without creating a new List<uint> just to add that one item. I'm almost certian there's some expression I could include which wouldn't require that. Anyone know?
16 Replies
reflectronic
reflectronic6mo ago
public uint[] Palette => [0, .. Colors.Take(255)];
public uint[] Palette => [0, .. Colors.Take(255)];
jcotton42
jcotton426mo ago
I wonder if [0u, ..Colors[..255]] is efficient
reflectronic
reflectronic6mo ago
the most efficient is
public uint[] Palette => [0, .. Colors.AsSpan(0, 255)];
public uint[] Palette => [0, .. Colors.AsSpan(0, 255)];
jcotton42
jcotton426mo ago
does mine actually copy Colors first before making the end result array?
reflectronic
reflectronic6mo ago
yes
jcotton42
jcotton426mo ago
ugh
BenMcLean
BenMcLeanOP6mo ago
I expect it to be making a copy.
reflectronic
reflectronic6mo ago
no, it's a useless copy
jcotton42
jcotton426mo ago
extra unnecessary copy
BenMcLean
BenMcLeanOP6mo ago
Oh why useless
reflectronic
reflectronic6mo ago
it copies the first 255 elements of Colors into a new uint[], then it copies that uint[] into the 256-element uint[] that you are returning the AsSpan avoids the first copy, it will copy directly from one array to the one you return
BenMcLean
BenMcLeanOP6mo ago
I should mention that this is inside of a readonly record struct so Colors shouldn't be monkeyed with Oh nice. Wait, there is no guarantee that colors will have 255 items It could be empty or could have up to 255 items
reflectronic
reflectronic6mo ago
Colors.AsSpan(0, int.Min(255, Colors.Length))
BenMcLean
BenMcLeanOP6mo ago
oh that's better, thanks I ended up with
public uint[] Palette => [0, .. Colors.AsSpan(0, Math.Min(255, Colors.Length))];
public uint[] Palette => [0, .. Colors.AsSpan(0, Math.Min(255, Colors.Length))];
reflectronic
reflectronic6mo ago
seems fine
BenMcLean
BenMcLeanOP6mo ago
I'm still getting used to collections syntax. Thanks.
Want results from more Discord servers?
Add your server