【问题标题】:Key-Value pair functionality inside a C# arrayC# 数组中的键值对功能
【发布时间】:2021-01-14 17:00:22
【问题描述】:

我正在尝试让一个“多维”锯齿状数组用于我的主要数据转换工作。我希望最里面的数组具有对象的键值对行为,但我不知道使用什么语法:

object[][][] courseData = new object[][][] 
  {
      new object[][]//chapter 1
      {
        new object[]
        {

          {id = 1, question = "question", answer = "answer"},
          //this one?
          (id = 2, question = "question", answer = "answer"),
          //or this one?
        }
      }
   }

这种语法大部分对我来说是新的,所以请告诉我我还犯了哪些其他错误。

如果数组中的键值对是不可能的,我将不得不使用未命名的索引引用,对吗?那将在构建时使用 () 和 [0] 作为参考,是吗?这个数组甚至可以在对象之外保存混合数据类型吗?

ps:将处理此数据的函数示例:

function mapOrder (array, order, key) {

  array.sort( function (a, b) {
    var A = a[key], B = b[key];

    if (order.indexOf(A) > order.indexOf(B)) {
      return 1;
    } else {
      return -1;
    }

  });

  return array;
};


reordered_array_a = mapOrder(courseData[0][0], orderTemplateSimple[0], id);

其中 orderTemplateSample[index] 是一个数字数组,用于从 courseData 转换“提取”数组的顺序。

我想在那里有 id 键引用,但如果我必须用理论上可行的数字替换它?

【问题讨论】:

    标签: c# syntax key-value dynamic-arrays jagged-arrays


    【解决方案1】:

    我们从inmost类型开始,也就是

      {id = 1, question = "question", answer = "answer"},
    

    不能是键值pair,因为它有三个属性:id, question, answer。 但是,你可以把它变成命名元组

      (int id, string question, string answer)
    

    声明将是

      (int id, string question, string answer)[][][] courseData = 
         new (int, string, string)[][][]
      {
          new (int, string, string)[][]//chapter 1
          {
            new (int, string, string)[]
            {
               // Long form
              (id : 1, question : "question", answer : "answer"),
        
               // Short form: we can skip id, question, answer names 
              (2, "question", "answer"),
            }
          }
       };
    

    现在你有一个 array(确切地说是数组的数组):

       int course = 1;
       int chapter = 1;
       int question = 2;
    
       // - 1 since arrays are zero based
       string mySecondAnswer = courseData[course - 1][chapter - 1][question - 1].answer;   
    

    【讨论】:

    • "OOoooh... AAAaaahh" 快速提问,事后添加属性会是什么样子?我的所有属性都需要在初始化时声明吗?
    • @BetterLife exe:从技术上讲,您可以使用ExpandoObject (System.Dynamic.ExpandoObject) 并动态添加属性,但我怀疑您是否真的需要它
    猜你喜欢
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多