C# 如何在c中将列表转换为锯齿数组?
我正在调用一个第三方API,它期望一个锯齿状数组作为输入,但我需要动态地构建这个列表C# 如何在c中将列表转换为锯齿数组?,c#,C#,我正在调用一个第三方API,它期望一个锯齿状数组作为输入,但我需要动态地构建这个列表 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { class Program {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var slots = new DateTime[][]
{
new DateTime[] {new DateTime(2020, 2, 14), new DateTime(2020, 2, 20)},
new DateTime[] {new DateTime(2020, 2, 15), new DateTime(2020, 2, 23)},
new DateTime[] {new DateTime(2020, 2, 16), new DateTime(2020, 2, 24)}
};
DateTime[][] slots2;
List<DateTime> appointments=new List<DateTime>();
appointments.Add(new DateTime(2020, 2, 14));
appointments.Add(new DateTime(2020, 2, 20));
slots2 = appointments.ToArray();
}
}
}
在上面的代码中,当我尝试使用datetime对象初始化锯齿状数组槽时,它工作正常,但当我尝试使用约会列表时,我发现槽2出现错误。如何使用日期时间列表初始化slot2以填充slots2?您需要先初始化它
// create 1 element in the first dimension
var slots2 = new DateTime[1][];
var appointments = new List<DateTime>
{
new DateTime(2020, 2, 14),
new DateTime(2020, 2, 20)
};
// add the second dimension to the first element you created
slots2[0] = appointments.ToArray();
编辑
为什么不直接使用列表并将它们投影到数组中呢
var appointments = new List<List<DateTime>>
{
new List<DateTime>
{
new DateTime(2020, 2, 14),
new DateTime(2020, 2, 20)
}
};
然后你可以添加更多
appointments.Add(new List<DateTime>
{
new DateTime(2020, 2, 14),
new DateTime(2020, 2, 20)
});
var slots2 = appointments.Select(x => x.ToArray()).ToArray();
你是说列表约会=新列表;或日期时间[]slots2;?目前,slots2是DateTime[]的一种类型,但约会等同于DateTime[]。我想用datetimeslot2的动态列表初始化slot2必须是一个锯齿数组,我想用动态列表初始化它。这就是我的问题。按照这个逻辑,你应该把你的约会列表改成一个列表。您当前拥有的是DateTime对象的一维数组,它不能是锯齿数组,因为锯齿数组是多维的。目前还不完全清楚slots2的预期值应该是什么。你能举个例子,说明你认为slots2的价值在你的问题中是什么样的吗?或者顶部的插槽是插槽2的预期值的一个示例?这与我想要的很接近,但并不完全是因为约会基于用户输入,并且长度可能会有所不同,这就是为什么我现在不知道在运行时在第一维度(即上述代码中的[1])中将有多少项
appointments.Add(new List<DateTime>
{
new DateTime(2020, 2, 14),
new DateTime(2020, 2, 20)
});
var slots2 = appointments.Select(x => x.ToArray()).ToArray();