0

Say I want to create (n) DataTables named DT(n)... how can I go about that in a loop.

Pseudo code below

int n=99;

for (int i = 0; i < n; i++)
{
    DataTable DT + n = new DataTable(); // <--- this
}

Is this possible?

3
  • Can you use an array? Commented Jun 5, 2014 at 23:10
  • No, that is not possible. But you could make an array of DataTables or some other collection of them. Commented Jun 5, 2014 at 23:11
  • 1
    Use Array Commented Jun 5, 2014 at 23:11

5 Answers 5

5

Store them in a data structure.

Enumerable.Range(0,n).Select(x => new DataTable()).ToArray()
Sign up to request clarification or add additional context in comments.

2 Comments

or simply Enumerable.Repeat(new DataTable(), n)
@TimSchmelter That's going to give you n references to the same instance of DataTable, not n instances of DataTable.
3

No, you can't have dynamic variable names in C#.

You can however, put them into an array (this is a much better approach anyways):

int n=99;
DataTable[] DT = new DataTable[99];

for (int i = 0; i < n; i++)
{
    DT[i] = new DataTable();
}

1 Comment

This is much more likely to be helpful to the OP than the fancier answers.
1

You can't create dynamically named variables in C#. For your purpose you are better off using Arrays or Dictionaries ( http://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx )

Comments

0

try

List<DataTable> DTs = new List<DataTable>();
int n =99;
for(int(i=0;i<n;i++)
{
    DataTable DT = new DataTable();
    DTs.Add(DT);
}

2 Comments

New is VB, new is C#. They don't mix :)
This answer turned up in the low quality review queue, presumably because you didn't explain some of the contents. If you do explain this (in your answer), you are far more likely to get more upvotes—and the questioner actually learns something!
0

Can you try this one

public List<T> CreateObjects<T>(int numbers) where T: new()
{
   List<T> _return = new List<T>();
   for (int i = 0; i <= numbers; i++)
   {
      _return.Add(new T());
   }

   return _return;

}

to use

var myList = CreateObjects<DataTable>(100);
var myList = CreateObjects<AnyClass>(100);

use any object type

2 Comments

While a nice, generic piece of code, this has no explanation and is effectively the same as the LINQ answer (but much more confusing since the question was never about generics).
yes I know, but this is just a example for get idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.