如何创建嵌套列表并返回自定义MyClass对象类型列表
Solution for Creating a Nested List of MyClass Objects
Got it, let's adjust your code to return a nested list of your custom MyClass objects instead of the string lists you're currently building. Your existing MyClass definition is good to go—we just need to modify the list creation logic to wrap each string in a MyClass instance.
Corrected Nested List Creation Method
Here's how to rewrite your list-building method to produce the structure you want:
// Returns a 3-level nested list of MyClass objects public List<List<List<MyClass>>> CreateNestedMyClassList() { return new List<List<List<MyClass>>> { // First-level container new List<List<MyClass>> { // Second level: single MyClass with name "A" new List<MyClass> { new MyClass("A") }, // Second level: two MyClass objects ("B" and "C") new List<MyClass> { new MyClass("B"), new MyClass("C") }, // Second level: two more MyClass objects ("D" and "E") new List<MyClass> { new MyClass("D"), new MyClass("E") } }, // Optional: add more first-level containers if your structure needs them new List<List<MyClass>> { new List<MyClass> { new MyClass("F") } } }; }
Key Changes Explained
- Type Alignment: Instead of
List<List<List<string>>>, we now useList<List<List<MyClass>>>, which matches your goal of returning nested custom objects. - Object Conversion: Every string from your original list is now passed to the
MyClassconstructor (new MyClass("A")), turning each string into an instance of your custom class. - Structure Preservation: The nested hierarchy (3 levels deep) stays exactly like your original code—you just swap out raw strings for
MyClassinstances.
Using the Method
To implement this in your code, call it and access elements like this:
var myNestedList = CreateNestedMyClassList(); // Get the name of the first object: "A" string firstObjectName = myNestedList[0][0][0].Name; // Get the name of the third object: "C" string thirdObjectName = myNestedList[0][1][1].Name;
If you need a different depth of nesting (like 2 levels instead of 3), just adjust the generic type accordingly. For example, List<List<MyClass>> would give you a two-level nested list.
内容的提问来源于stack exchange,提问作者GET1NE
相关产品推荐
相关产品推荐

