使用C#在一个ConcurrentDictionary中输入和获取数组中的值

本文关键字:输入 获取 数组 ConcurrentDictionary 一个 使用 | 更新日期: 2023-09-27 18:29:07

到目前为止,我一直在使用简单数组来输入和获取必要的信息。

第一个例子如下:

            // ===Example 1. Enter info ////
            string[] testArr1 = null;
            testArr1[0] = "ab";
            testArr1[1] = "2";
            // ===Example 1. GET info ////
            string teeext = testArr1[0];
            // =======================

第二个例子:

            // ====== Example 2. Enter info ////
            string[][] testArr2 = null;
            List<int> listTest = new List<int>();
            listTest.Add(1);
            listTest.Add(3);
            listTest.Add(7);
            foreach (int listitem in listTest)
            {
                testArr2[listitem][0] = "yohoho";
            }
            // ====== Example 2. Get info ////
            string teeext2 = testArr2[0][0];
            // =======================

但现在我正在尝试为每个数组分配一个标识号,这样我就可以在一个ConcurrentDictionary中识别多个不同的数组

如何在字典中输入和获取数组中的信息

看,我们有两个标识符和两个字典:

            decimal identifier1 = 254;
            decimal identifier2 = 110;
            ConcurrentDictionary<decimal, string[]> test1 = new ConcurrentDictionary<decimal, string[]>();
            ConcurrentDictionary<decimal, string[][]> test2 = new ConcurrentDictionary<decimal, string[][]>();

我在想象这样的事情:

//////////Example 1
//To write info
test1.TryAdd(identifier1)[0] = "a";
test1.TryAdd(identifier1)[1] = "b11";
test1.TryAdd(identifier2)[0] = "152";
//to get info
string value1 = test1.TryGetValue(identifier1)[0];
string value1 = test1.TryGetValue(identifier2)[0];
//////////Example 2
//To write info: no idea
//to get info: no idea

附言:上面的代码不起作用(因为它是自制的)。。那么,通过ID将信息输入ConcurrentDictionary中的string[]和string[][]的正确方法是什么呢?(并将其取出)

使用C#在一个ConcurrentDictionary中输入和获取数组中的值

给定您的声明

decimal identifier1 = 254;
decimal identifier2 = 110;
ConcurrentDictionary<decimal, string[]> test1 = new ConcurrentDictionary<decimal, string[]>();
ConcurrentDictionary<decimal, string[][]> test2 = new ConcurrentDictionary<decimal, string[][]>();

你可以使用这样的代码

  test1[identifier1] = new string[123];
  test1[identifier1][12] = "hello";
  test2[identifier2] = new string[10][];
  test2[identifier2][0] = new string[20];
  test2[identifier2][0][1] = "world";

输入您的数据。以下是访问您输入的数据的示例:

  Console.WriteLine(test1[identifier1][12] + " " + test2[identifier2][0][1]);

不过,我必须说,这样的代码往往非常复杂,很难调试,尤其是对于test2的情况。你确定要使用锯齿状数组吗?