【问题标题】:How can I convert an list of object to an array of list of object with each array index having 2 count?如何将对象列表转换为对象列表数组,每个数组索引都有 2 个计数?
【发布时间】:2020-08-05 18:29:12
【问题描述】:

我希望每个人都在这场危机中做得很好。

好的,这是我的对象列表,其中包含名称和值的对象:

我喜欢用这个对象列表做的是我需要把它转换成一个 in 对象列表的数组,每个索引的数组计数为 2。例如

当我们将列表的总数除以 2 时,它是 8。 所以我的数组将有 4 个索引,其中包含该对象的列表。但是在数组的每个索引上,列表的计数将是每个索引 2。

考虑上面第一个索引的例子:

Array[1 first index (rest will be same)] => List[Count = 2 of object] => {object containg the name and value}

到目前为止,我尝试的是通过分离键和值并使用内部循环和其他一些方法循环计数 2,但似乎无法使其满足我的需要。我会很感激你的帮助。

【问题讨论】:

  • var myArray = new List<AdditionalPropertyJsonModel>[list.Count / 2];
  • 嗨@RufusL,所以我尝试了您提到的上述代码。它将列表划分为我想要的数组,但数组中的列表为空。
  • 是的,您需要从列表中填充它
  • 哦,对了。谢谢您的帮助。我会尽力让你知道。

标签: c# asp.net arrays list object


【解决方案1】:

这里有一些示例代码可以帮助您入门,但您需要验证初始列表是否具有偶数:

// This is a representation your current list, the actual one is slightly different
var list = new List<AdditionalPropertyJsonModel>
{
    new AdditionalPropertyJsonModel {name = "one", value = "two"},
    new AdditionalPropertyJsonModel {name = "three", value = "four"},
    new AdditionalPropertyJsonModel {name = "five", value = "six"},
    new AdditionalPropertyJsonModel {name = "seven", value = "eight"},
    new AdditionalPropertyJsonModel {name = "nine", value = "ten"},
    new AdditionalPropertyJsonModel {name = "eleven", value = "twelve"},
};

// Create an array that's half the size of the list
var myArray = new List<AdditionalPropertyJsonModel>[list.Count / 2];

// Populate the array so that each item is a list of two items from the original list
for (var i = 0; i < myArray.Length; i ++)
{
    myArray[i] = new List<AdditionalPropertyJsonModel>
    {
        // Since each index of the array represents two items from the list, we
        // multiply the array index by 2 on each iteration to get the list indexes
        // of the values we want to add to this two-item list for the array index
        list[i * 2],
        list[i * 2 + 1]
    };
}

【讨论】:

  • 完美。它按我的意愿工作。不知道为什么我没有想到这个:P。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多