C# 程序打印列表的所有子列表
csharpprogrammingserver side programming更新于 2025/9/20 21:11:00
首先,创建一个列表 −
List list = new List();
这里的字符串是 “xyz” 我们将为其找到子列表。在循环过程中,我们将声明另一个列表,该列表将在每次真正的迭代中生成子列表 −
for (int i = 1; i < str.Length; i++) {
list.Add(str[i - 1].ToString());
List newlist = new List();
for (int j = 0; j < list.Count; j++) {
string list2 = list[j] + str[i];
newlist.Add(list2);
}
list.AddRange(newlist);
}
以下是完整代码 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string str = "xyz";
List list = new List();
for (int i = 1; i < str.Length; i++) {
list.Add(str[i - 1].ToString());
List newlist = new List();
for (int j = 0; j < list.Count; j++) {
string list2 = list[j] + str[i];
newlist.Add(list2);
}
list.AddRange(newlist);
}
list.Add(str[str.Length - 1].ToString());
list.Sort();
Console.WriteLine(string.Join(Environment.NewLine, list));
}
}
}
输出
x xy xyz xz y yz z

