Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chương trình C# in tất cả các danh sách con (sublists) của một list

Trước tiên, tạo một list:

List list = new List();

Chuỗi ở đây là "xyz" để tìm các sublist. Khi lặp, khai báo một list khác để tạo sublist ở mỗi lần lặp true:

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); 
}

Code hoàn chỉnh:

Ví dụ

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)); 
        } 
    } 
}

Kết quả

x
xy
xyz
xz
y
yz
z