Click here to Skip to main content
15,891,682 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello masters,

I want to ask if it is possible to create variable number of lists.
C#
public void CreateClusters(int NumberOfClusters)
       {
           for (int i = 1; i < NumberOfClusters ; i++)
           {
               List<Color> Cluster(i) = new List<Color>();
           }
       }

For example when the i is 1, i want to create a color list named "Cluster1"

I am new at programming and thank you for your help.
Posted

This is two folded. Basically you can create new named variables on the fly by generating for example code that is then compiled. However, since you mentioned that you're new to programming, I would say that this is a wrong approach. Do you really need new variables or just new instances of a predefined class?

Based on the description you have given I suppose you want to separate different instances of Color in your list. Would a Dictionary[^] satisfy your requirements?
 
Share this answer
 
Comments
VJ Reddy 12-May-12 0:27am    
Dictionary is a good suggestion. 5!
Wendelius 12-May-12 4:15am    
Thank you :)
Just use some simple logic. From your code, it looks like you should understand that a generic list is a collection of anything. So, what can act as a collection of variable number of lists? Not surprisingly, a list of lists:

C#
using ColorList = System.Collections.Generic.List<Color>;
using ListOfColorLists = System.Collections.Generic.List<System.Collections.Generic.List<Color>>;

//...

public ListOfColorLists CreateClusters(int numberOfClusters) {
    ListOfColorLists list = new ListOfColorLists();
    for (int index = 0; index < numberOfClusters; ++index)
        list.Add(new ColorList());
    return list;
} //CreateClusters


Please pay attention for some fixed I've made. First of all, you are trying to execute your loop NumberOfClusters − 1 times; you would miss one element, so the fix is to start with zero index. I also improved your naming to meet Microsoft naming conventions. Loop variable is renamed because one-character names are bad (how would you do search, for example?); ++index provides better performance then index++ without change in results. (It looks strange, but try to test it.) Return value is added to your method, otherwise creation of objects would be pointless and eventually would cause destruction of them by the Garbage Collector (http://en.wikipedia.org/wiki/Garbage_collector_%28computing%29[^]).

—SA
 
Share this answer
 
v4
Comments
VJ Reddy 12-May-12 0:24am    
Nice answer and suggestions. 5!
Sergey Alexandrovich Kryukov 12-May-12 0:27am    
Thank you, VJ.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900