0

I have an Array sample:

string[] arr = new string[5];
arr[0] = "a";
arr[1] = "b";
arr[2] = "c";
arr[3] = "d";

And I want to do this:

arr["a"] = "b";
arr["c"] = "d";

This is my code and it didn't solve my problem:

for (int i =0; i < str.Length; i++)
{
    if (i + 1 < str.Length)
    {
        string key = str[i];
        arr[key] = str[i + 1];
        MessageBox.Show(key);

    }

}
Paul Karam
  • 4,052
  • 8
  • 30
  • 53

4 Answers4

1

The indexer in c# is always an int. You have to use a different data structure if you want to use a string as index. For example use Dictionary

var arr = new Dictionary<string, string>();
arr[key] = str[i + 1];
Fabiano
  • 5,124
  • 6
  • 42
  • 69
1

You are looking for dictionary (when given a key, e.g. "a", "b" you want to have the corresponding value "c" or "d"). Linq solution:

  string[] arr = new string[5];
  arr[0] = "a";
  arr[1] = "b";
  arr[2] = "c";
  arr[3] = "d";

  Dictionary<string, string> dict = Enumerable
    .Range(0, arr.Length / 2)
    .ToDictionary(i => arr[2 * i], i => arr[2 * i + 1]);

Test

 string report = string.Join(Environment.NewLine, dict
   .Select(pair => $"arr[\"{pair.Key}\"] = \"{pair.Value}\";"));

 Console.Write(report);

Outcome:

 arr["a"] = "b";
 arr["c"] = "d";
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • I get this error Additional information: An item with the same key has already been added. –  Jun 20 '17 at 09:40
  • @Mido Bona: what is your *actual data*? You are supposed to get such an error if you have *key conflict*, e.g. `arr = ["a", "a", "b", "c"]` - what is the expected result - `dict["a"] == "b"` or `dict["a"] == "c"`? – Dmitry Bychenko Jun 20 '17 at 09:42
  • arr = ["a", "b", "c", "d"] –  Jun 20 '17 at 09:44
  • @Mido Bona: I've run my code and it returns the outcome I provided; I've changed the input into `string[] arr = new string[] {"a", "b", "c", "d"}` and I've got the same outcome. – Dmitry Bychenko Jun 20 '17 at 09:47
  • @Mido Bona: you are, probably, doing something like `arr = new string[10]; arr[0] = "a"; arr[1] = "b"; arr[2] = "c"; arr[3] = "d";` - the array has `10` items, but only first `4` of them are keys and values. Is it your case? – Dmitry Bychenko Jun 20 '17 at 09:52
  • arr = new string[4]; arr[0] = "a"; arr[1] = "b"; arr[2] = "c"; arr[3] = "d"; –  Jun 20 '17 at 09:54
  • In fact I am contacting api And get results other than in the example but there are some empty values Do you want to see the ِArray ? –  Jun 20 '17 at 09:56
  • @Mido Bona: yes, and, please, specify what do you want to do with empty values (what is the *desired outcome*) – Dmitry Bychenko Jun 20 '17 at 09:59
  • Empty Values Can Be Not Empty "id","*1","customer","admin","actual-profile","a","username","n7kv5z","password","qngdxk","shared-users","1","wireless-psk","","wireless-enc-key","","wireless-enc-algo","none","uptime-used","7h13m53s","download-used","252818743","upload-used","29738854","last-seen","jun/17/2017 14:37:49","active","false","incomplete","false","disabled","false" –  Jun 20 '17 at 10:04
  • First Values Impossible Empty –  Jun 20 '17 at 10:07
  • Can You Help Me ? –  Jun 20 '17 at 10:13
  • @Mido Bona: I see! **My bad**; I've edited the answer; Sorry for my misunderstanding: we should treat even items (zero-based: 0, 2, 4...) as keys add odd ones (1, 3, 5...) as values – Dmitry Bychenko Jun 20 '17 at 10:13
  • @Mido Bona: please, try my edit it should start working now – Dmitry Bychenko Jun 20 '17 at 10:17
  • @Mido Bona: `string myId = dict["id"];` or `string myId; if (dict.TryGetValue("id", out myId)) {/*we have an "id" and its value is in myId*/} else {/* no "id" in the dictionary */}` – Dmitry Bychenko Jun 20 '17 at 10:20
0

you should use

OrderedDictionary

msdn

here is reposted example:

    // The following code example enumerates the elements of a OrderedDictionary.
using System;
using System.Collections;
using System.Collections.Specialized;

public class OrderedDictionarySample
{
    public static void Main()
    {

        // Creates and initializes a OrderedDictionary.
        OrderedDictionary myOrderedDictionary = new OrderedDictionary();
        myOrderedDictionary.Add("testKey1", "testValue1");
        myOrderedDictionary.Add("testKey2", "testValue2");
        myOrderedDictionary.Add("keyToDelete", "valueToDelete");
        myOrderedDictionary.Add("testKey3", "testValue3");

        ICollection keyCollection = myOrderedDictionary.Keys;
        ICollection valueCollection = myOrderedDictionary.Values;

        // Display the contents using the key and value collections
        DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);

        // Modifying the OrderedDictionary
        if (!myOrderedDictionary.IsReadOnly)
        {
            // Insert a new key to the beginning of the OrderedDictionary
            myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1");

            // Modify the value of the entry with the key "testKey2"
            myOrderedDictionary["testKey2"] = "modifiedValue";

            // Remove the last entry from the OrderedDictionary: "testKey3"
            myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1);

            // Remove the "keyToDelete" entry, if it exists
            if (myOrderedDictionary.Contains("keyToDelete"))
            {
                myOrderedDictionary.Remove("keyToDelete");
            }
        }

        Console.WriteLine(
            "{0}Displaying the entries of a modified OrderedDictionary.",
            Environment.NewLine);
        DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);

        // Clear the OrderedDictionary and add new values
        myOrderedDictionary.Clear();
        myOrderedDictionary.Add("newKey1", "newValue1");
        myOrderedDictionary.Add("newKey2", "newValue2");
        myOrderedDictionary.Add("newKey3", "newValue3");

        // Display the contents of the "new" Dictionary using an enumerator
        IDictionaryEnumerator myEnumerator =
            myOrderedDictionary.GetEnumerator();

        Console.WriteLine(
            "{0}Displaying the entries of a \"new\" OrderedDictionary.",
            Environment.NewLine);

        DisplayEnumerator(myEnumerator);

        Console.ReadLine();
    }

    // Displays the contents of the OrderedDictionary from its keys and values
    public static void DisplayContents(
        ICollection keyCollection, ICollection valueCollection, int dictionarySize)
    {
        String[] myKeys = new String[dictionarySize];
        String[] myValues = new String[dictionarySize];
        keyCollection.CopyTo(myKeys, 0);
        valueCollection.CopyTo(myValues, 0);

        // Displays the contents of the OrderedDictionary
        Console.WriteLine("   INDEX KEY                       VALUE");
        for (int i = 0; i < dictionarySize; i++)
        {
            Console.WriteLine("   {0,-5} {1,-25} {2}",
                i, myKeys[i], myValues[i]);
        }
        Console.WriteLine();
    }

    // Displays the contents of the OrderedDictionary using its enumerator
    public static void DisplayEnumerator(IDictionaryEnumerator myEnumerator)
    {
        Console.WriteLine("   KEY                       VALUE");
        while (myEnumerator.MoveNext())
        {
            Console.WriteLine("   {0,-25} {1}",
                myEnumerator.Key, myEnumerator.Value);
        }
    }
}

/*
This code produces the following output.

   INDEX KEY                       VALUE
   0     testKey1                  testValue1
   1     testKey2                  testValue2
   2     keyToDelete               valueToDelete
   3     testKey3                  testValue3


Displaying the entries of a modified OrderedDictionary.
   INDEX KEY                       VALUE
   0     insertedKey1              insertedValue1
   1     testKey1                  testValue1
   2     testKey2                  modifiedValue


Displaying the entries of a "new" OrderedDictionary.
   KEY                       VALUE
   newKey1                   newValue1
   newKey2                   newValue2
   newKey3                   newValue3

*/
Sebastian 506563
  • 6,980
  • 3
  • 31
  • 56
  • sorry this solution not solve my problem Because I do not add value manually –  Jun 20 '17 at 09:23
  • this is an example how to use ordereddictionary, you do not have to use to do it manualy. You can put inserts into array. We wont write you an exact code because we do not really know what you want to accomplish. – Sebastian 506563 Jun 20 '17 at 09:25
  • @MidoBona in your question you add the value manually: arr[key] = str[i + 1]; – Fabiano Jun 20 '17 at 09:26
0

I think you want a dictionary:

Dictionary<string, string> dict = new Dictionary<string, string>();
for(int i = 0; i < arr.Length; i += 2)
{
    dict.Add(arr[i], arr[i + 1])
}

One thing to watch with this, is that the keys will need to be unique, so you'll want to add some error handling to catch duplicates.

JCoyle
  • 100
  • 9
  • What do you mean? This will result in dict["a"] == "b" and dict["c"] == "d" You cannot access your array by a string indexer, you'll need to use a dictionary, and this will give you the result you need – JCoyle Jun 20 '17 at 09:36