Search code examples
c#variablesconcatenation

How to turn values in variables into array indexes


Hoping I can explain this clearly ... I have a collection of variables:

static string sRunnerSetName, sFH, sR1, sH2, sR2, sH3, sR3, sH4, sR4, sH5, sR5 = "";
static int iRunnerSetName, iFH, iR1, iH2, iR2, iH3, iR3, iH4, iR4, iH5, iR5 = 0;

Each of the int variables hold a unique value, which provide the order that the corresponding string variables need to be combined and put into a concatenated string. So iFH holds the sorting/order-number position for where the string sFH will be positioned in the concatenated string.

I'm just stuck with how to use the values in each int to create the order of strings?

As an example -

 iFH = 2; i1R = 0; i2R = 1;
 sFH = "z"; s1R = "x"; s2R = "y";

Looking to use the values in the integer variables to create the order/position of each string so that the concatenated result of the above would be "xyz".


Solution

  • Create a class holding a string and an int:

    class Item
    {
        public string Description {get;set;}
        public int SortOrder {get;set;}
    }
    

    Create a list (or another collection, which fits better to your needs) of these items:

    List<Item> list = new List<Item>
    {
       new Item { Description = "Test", SortOrder = 4 },
       new Item { Description = "Test2", SortOrder = 3 },
       new Item { Description = "sadf", SortOrder = 1 },
       new Item { Description = "Example", SortOrder = 2 },
       new Item { Description = "something", SortOrder = 5 }
    };
    

    You can use LINQ to sort your list:

    list = list.OrderBy(x => x.SortOrder).ToList();
    

    You can then output it on console:

    Console.WriteLine(string.Join("\n", list.Select(x => x.Description)));
    

    Try it online