C
C#14mo ago
triplemocha

How to replace elements in an array of type T?

I have an Array2D<T> class that can take integer, reference types, etc. They are stored in this:
private T[] m_array = new T[width * height];
private T[] m_array = new T[width * height];
I have a method here that should replace elements.
void Replace(T from, T to)
{
}
void Replace(T from, T to)
{
}
I can't find any existing replace method. Any suggestions?
8 Replies
boiled goose
boiled goose14mo ago
uhm wouldn't replace take also a index as argument? also by replace you mean assigning?
triplemocha
triplemocha14mo ago
This would change any element that matched from and replace it with to.
occluder
occluder14mo ago
Maybe m_array[Array.IndexOf(m_array, from)] = to;?
boiled goose
boiled goose14mo ago
yeah, that but with a loop
occluder
occluder14mo ago
void Replace(T from, T to)
{
int i;
while ((i = Array.IndexOf(m_array, from)) != -1)
{
m_array[i] = to;
}
}
void Replace(T from, T to)
{
int i;
while ((i = Array.IndexOf(m_array, from)) != -1)
{
m_array[i] = to;
}
}
like that maybe
triplemocha
triplemocha14mo ago
It works, thanks!
boiled goose
boiled goose14mo ago
from is kind of a reserved word just remember it
triplemocha
triplemocha14mo ago
It's a contextual keyword.