0

How can I create new struct objects via a loop. Foreach through a list's elements for e.g.?

Here is my struct:

public struct TestStruct
{
    public int value1;
    public int value2;
    public List<string> firststructlist;

    public TestStruct(int bab, int bob)
    {
        value1 = bab;
        value2 = bob;
        firststructlist = new List<string>();
     }
     
    public void Add(string value)
    {
        if (firststructlist == null)
            firststructlist = new List<string>();
        firststructlist.Add(value);
    }
}

It seems OK, I can create new objects "manually"

TestStruct second = new TestStruct(1, 2);
second.value1 = 8;
second.value2 = 9;
second.firststructlist.Add("panapinom");
second.firststructlist.Add("zsakfos");

But failed to do it via loop during run-time. I imagined something like this (this does not work of course):

foreach (string something in anything)
{
    TestStruct "something" = new TestStruct(1, 2);
    // new TestStruct for all "something" in the list
}`enter code here`

Please help!

Stefan
  • 652
  • 5
  • 19
Ur Pocok
  • 21
  • 2
  • 1
    Yep, as the dupe suggests - this is what `Dictionary` is for – Jamiec Aug 26 '21 at 13:03
  • 1
    Every time you think you have to use something like `Variable1`, `Variable2` etc... it means you need an array/list/whatever collection – Cid Aug 26 '21 at 13:04

0 Answers0