Convert VB code to C # using array and redim preserver keyword

This is my VB code:

If TxtStr(i) = "#" And TxtStr(i + 1) = "]" Then
    RefStr = RefStr & "]"
    ReDim Preserve RefStrLinks(1, RefStrLinkIndex)
    RefStrLinks(0, RefStrLinkIndex) = RefStr
    RefStr = RefStr.Replace("[#", String.Empty)
    RefStr = RefStr.Replace("#]", String.Empty)
    RefStrLinks(1, RefStrLinkIndex) = RefStr
    RefStrLinkIndex = RefStrLinkIndex + 1
    RefStr = String.Empty
    RefStrFound = False
End If

      

This is my converted code in C #; RefStrLinks

declared as:

string[,] RefStrLinks = null;

      

But it gives a compilation error because of ReDim Preserve

whenever I run this:

if (TxtStr[i].ToString() == "#" & TxtStr[i + 1].ToString() == "]")
{
    RefStr = RefStr + "]";
    Array.Resize<string>(ref RefStrLinks, RefStrLinkIndex + 1);
    RefStrLinks[0, RefStrLinkIndex] = RefStr;
    RefStr = RefStr.Replace("[#", string.Empty);
    RefStr = RefStr.Replace("#]", string.Empty);
    RefStrLinks(1, RefStrLinkIndex) = RefStr;
    RefStrLinkIndex = RefStrLinkIndex + 1;
    RefStr = string.Empty;
    RefStrFound = false;
}

      

Does anyone understand why?

+3


source to share


1 answer


on right; I think the real problem is that you have a two dimensional array; RefStrLinks

is not string[]

, but rather is string[,]

, with dimension 2 on the first axis. Array.Resize

works only with vectors ("vector" is a one-dimensional array with base index 0, ie string[]

).

Quite frankly, I would replace the whole thing (re-dimming the array, or using it Array.Resize

for an element is absurdly expensive) with something like:

List<SomeBasicType> list = ...
...
// where "foo" and "bar" are the two values that you intend to store per item
var item = new SomeBasicType(foo, bar);
list.Add(item);

      



where possible SomeBasicType

, an immutable structure that takes two lines. Or, more simply, in C # "current": value type tuples:

// declare the list (change the names to something meaningful for your code)
var list = new List<(string name, string url)>();

// ... add values efficiently

string name = "whatever"; // your per-item code goes here
string url = "some value"; // and here
list.Add((name, url));

// ... show that we have the data

foreach(var item in list)
{
    Console.WriteLine($"{item.name} / {item.url}");
}

      

+5


source







All Articles