繁体   English   中英

c#将第一个值转换为键

[英]c# Convert First Values To Keys

我有一个Array示例:

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

我想这样做:

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

这是我的代码,但没有解决我的问题:

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);

    }

}

c#中的索引器始终是int 如果要使用字符串作为索引,则必须使用其他数据结构。 例如使用字典

var arr = new Dictionary<string, string>();
arr[key] = str[i + 1];

您正在寻找字典 (给定 ,例如"a""b"您想要具有相应的值"c""d" )。 Linq解决方案:

  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]);

测试

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

 Console.Write(report);

结果:

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

你应该使用

OrderedDictionary

msdn

这是重新发布的示例:

    // 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

*/

我认为您想要一本字典:

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

需要注意的一件事是密钥必须是唯一的,因此您需要添加一些错误处理以捕获重复项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM