我是C#的新手,来自PHP语言背景,在那里多维数组就像公园里的散步一样。
如何在C#中创建带有SortedList的嵌套/多维数组?我相信通过阅读,SortedList在功能方面可能是最具可比性的。我尝试了以下方法,但它抛出了错误:
SortedList arr = new SortedList();
arr.Add("hello",new SortedList());
arr.hello.Add("world",new SortedList());发布于 2017-06-01 03:56:35
那这个呢。
class NestedSortedList<T> : SortedList<T, NestedSortedList<T>> { }和测试..
internal class Program
{
private static void Main(string[] args)
{
var nestedSortedList = new NestedSortedList<string>();
nestedSortedList.Add("1", new NestedSortedList<string>());
nestedSortedList.Add("2", new NestedSortedList<string>());
nestedSortedList.Add("3", new NestedSortedList<string>());
nestedSortedList["1"].Add("11", new NestedSortedList<string>());
nestedSortedList["2"].Add("21", new NestedSortedList<string>());
nestedSortedList["2"].Add("22", new NestedSortedList<string>());
foreach (var item in nestedSortedList)
{
Console.WriteLine(item);
foreach (var value in item.Value.Values)
{
Console.WriteLine(value);
}
Console.WriteLine();
}
Console.ReadLine();
}
}这是输出

不创建NestedSortedList类的EDIT>>>
你可以尝试以下方法,尽管你将不得不处理所有这些丑陋的造型。
internal class Program
{
private static void Main(string[] args)
{
var sortedList = new SortedList();
sortedList.Add("1", new SortedList());
sortedList.Add("2", new SortedList());
sortedList.Add("3", new SortedList());
((SortedList)sortedList["1"]).Add("11", new SortedList());
((SortedList)sortedList["2"]).Add("21", new SortedList());
((SortedList)sortedList["2"]).Add("22", new SortedList());
foreach (DictionaryEntry dictionaryEntry in sortedList)
{
Console.WriteLine("Key: {0}, Value: {1}",dictionaryEntry.Key,dictionaryEntry.Value);
foreach (DictionaryEntry innerDictionaryEntry in (SortedList)dictionaryEntry.Value)
{
Console.WriteLine("Inner >>> Key: {0}, Value: {1}", innerDictionaryEntry.Key,
innerDictionaryEntry.Value);
}
Console.WriteLine();
}
Console.ReadLine();
}
}输出结果是...

但请当心。由于非泛型SortedList接收类型 object 作为键和值,这意味着您可以存储所需的任何对象,但您始终需要正确地转换它们,以便将它们用作其原始类型
希望这能有所帮助
发布于 2017-06-01 03:56:20
创建一个类
public class MyList
{
string name { get; set;}
List<MyList> children { get; set; }
}或
public class MyList
{
SortedList<string, MyList> children = new SortedList<string, MyList>();
}https://stackoverflow.com/questions/44292847
复制相似问题