C# program to print all sublists of a list

CsharpProgrammingServer Side Programming

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
raja
Published on 08-Aug-2018 16:02:39
Advertisements