2

I've found a few threads on this for other languages but nothing for C#...

Basically, what I need is to instantiate a class with a different name each time (in order to be able to create links between the classes)

My current code:

foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
}

This creates a new NodeViewModel for every row in the table. What I really need is for each NodeViewModel to have a different name, but I have no idea how to do this.

I tried using a simple int in the loop but I can't add a variable into the class instance name. The (obviously wrong) code is here:

int i = 0;
foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node+i = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
    i++;
}

I figured by this point that I should be doing things differently and this was probably a terrible idea, but I'd like some advice! If it is possible I'd like to know - otherwise, some alternatives would be very helpful =)

Thanks!

2 Answers 2

7

I think you're looking for a collection. You can use a List<NodeViewModel>.

var nodelist = new List<NodeViewModel>();
foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
    nodelist.Add(node);
}

Now you can access every node in the list via index, for example:

NodeViewModel nvm = nodelist[0];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that is exactly what I needed!
0

Tim Schmelter right. And, of course, wou can use Linq for more elegant code:

var nodelist = RoutingObjects.Rows.Select(dataRow=>CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString())

1 Comment

Instead of RoutingObjects.Rows.Select you have to use RoutingObjects.AsEnumerable().Select because a DataRowCollection doesn't implement IEnumerable<DataRow> but only IEnumerable.

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.