0

I've got a little problem. In my program i need a list of SqlCommand objects. So there is a piece of code:

List<SqlCommand> commands;
int i = 0;
foreach (string komenda in komendy)
{
    commands.ElementAt<SqlCommand>(i) = new SqlCommand(komenda, dostep());
    i++;
}

where komendy is a list of string with command strings and function dostep() is returning connection (SqlConnection object).

I've got an error: The left-hand side of an assignment must be a variable, property or indexer for commands.ElementAt< SqlCommand >(i) and i really don't understand why.

2 Answers2

1

ElementAt is a method that returns the object at the specified index in the sequence, you are using it as it was an assignement to add elements to the list.

When using a List(of Type), to add elements to the list you use the Add method without specifying a precise location. (This is the main job of arrays) Just use.....

 commands.Add(new SqlCommand(komenda, dostep()));

and, of course, before using an object, you need to initialize it with

List<SqlCommand> commands = new List<SqlCommand>();

As a side note, I am a bit perplexed by your approach to build a list of SqlCommand with the SqlConnection object initialized. This could be a very resource hog if you have many commands.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • +1 for not only providing a solution, but answering the question why the exception was thrown. – Corak Apr 13 '13 at 07:54
0

Why don't you use LINQ:

List<SqlCommand> commands = komendy.Select(x => new SqlCommand(x, dostep())).ToList();

With your approach you're missing commands initialization

List<SqlCommand> commands = new List<SqlCommand>();

And you should use Add method instead of ElementAt:

foreach (string komenda in komendy)
{
    commands.Add(new SqlCommand(komenda, dostep()));
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • Oh, i don't know why i forgot about Add function. Thank you very much for help. –  Apr 13 '13 at 07:55