C# program to print all sublists of a list


Firstly, create a list −

List list = new List();

The string here is “xyz” for which we will find the sublists. While looping we will declare another list, that would generate sublists on every true iteration −

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

The following is the complete code −

Example

 Live Demo

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

Output

x
xy
xyz
xz
y
yz
z

Updated on: 20-Jun-2020

440 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements