C
C#3w 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
reflectronic3w ago
public uint[] Palette => [0, .. Colors.Take(255)];
public uint[] Palette => [0, .. Colors.Take(255)];
jcotton42
jcotton423w ago
I wonder if [0u, ..Colors[..255]] is efficient
reflectronic
reflectronic3w ago
the most efficient is
public uint[] Palette => [0, .. Colors.AsSpan(0, 255)];
public uint[] Palette => [0, .. Colors.AsSpan(0, 255)];
jcotton42
jcotton423w ago
does mine actually copy Colors first before making the end result array?
reflectronic
reflectronic3w ago
yes
jcotton42
jcotton423w ago
ugh
BenMcLean
BenMcLean3w ago
I expect it to be making a copy.
reflectronic
reflectronic3w ago
no, it's a useless copy
jcotton42
jcotton423w ago
extra unnecessary copy
BenMcLean
BenMcLean3w ago
Oh why useless
reflectronic
reflectronic3w 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
BenMcLean3w 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
reflectronic3w ago
Colors.AsSpan(0, int.Min(255, Colors.Length))
BenMcLean
BenMcLean3w 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
reflectronic3w ago
seems fine
BenMcLean
BenMcLean3w ago
I'm still getting used to collections syntax. Thanks.