Question record type arrays/lists

cfrank2000

Well-known member
Joined
Mar 6, 2021
Messages
71
Programming Experience
Beginner
Hi
my name is frank struggling with record type arrays/lists (pascal programing analogies). I am trying to build kind of record type array or list but as a beginner I don't understand how does it work, specially accessing it by reline or by row, work with it, display it. I was thinking about data table option also but I need help with this matter. I am posting my instance below, please help me thank you, frank

ConsoleApp2listtyplist1:
using System;
using System.Collections.Generic;
using System.Collections;

namespace ConsoleApp2listtyplist1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Collection of string 
            string[] animals = { "bird 1", "bird 1", "bird 1" };
            string[] animals2 = { "bird 12", "bird 12", "bird 12" };
            string[] animals3 = { "bird 13", "bird 13", "bird 13" };
            // Create a List and add a collection 
            List<string> animalsList = new List<string>();
            animalsList.AddRange(animals);
            animalsList.AddRange(animals2);
            animalsList.AddRange(animals3);
            foreach (string a in animalsList)
                Console.WriteLine(a);

            ArrayList a1 = new ArrayList();
            a1.Add(1);
            a1.Add("Example");
            a1.Add(true);

            Console.WriteLine(a1[0]);
            Console.WriteLine(a1[1]);
            Console.WriteLine(a1[2]);
            Console.ReadKey();
            Console.WriteLine("Hello World!");

            List<string> array1 = new List<string>();
            array1.Add("test");

            List<List<string>> array2 = new List<List<string>>();
            array2.Add(array1);

            List<ArrayList> alsList = new List<ArrayList>();
        }
    }
}
 
The C# equivalents to the Pascal RECORD type is are classes and struct. In Pascal, if you wanted to have an array of strings inside the RECORD, you would declare it inside the the RECORD. The same is true for C#. If you want an array of strings in a class or struct, you would declare it inside as well. And similar to Pascal, if you want an array record types, you would declare an array of that record type, in C# you would also declare and array of the class or struct type.
 
Generally speaking, you would only use arrays for internal use in a class. If you want to expose any data outside an object then you should use properties and if you want to expose a list of data then you should use a read-only property of a collection type. That way, the consumer can get the existing collection in order to get, set, add and remove items but they cannot replace the existing collection entirely. E.g.
C#:
public class Person
{
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public List<Person> Children { get; } = new List<Person>();
}
Here, the Person class has two basic properties for the person's given and family names and a read-only collection property that contains other Person objects that represent that person's children. You might use that like this:
C#:
// It's OK to use an array here because it is for internal use.
var people = new[]
             {
                 new Person {GivenName = "Peter", FamilyName = "Smith"},
                 new Person {GivenName = "Paul", FamilyName = "Jones"},
                 new Person {GivenName = "Mary", FamilyName = "Williams"}
             };

var peter = people[0];

peter.Children.AddRange(new[]
                        {
                            new Person {GivenName = "John", FamilyName = "Smith"},
                            new Person {GivenName = "Jane", FamilyName = "Smith"}
                        });

foreach (var person in people)
{
    Console.WriteLine($"{person.GivenName} {person.FamilyName}");

    if (person.Children.Any())
    {
        Console.WriteLine("Children:");

        foreach (var child in person.Children)
        {
            Console.WriteLine($"{child.GivenName} {child.FamilyName}");
        }
    }
    else
    {
        Console.WriteLine("No children");
    }
}
In this case, the collection property in the Person class also contains Person objects, but your types can refer to any other types you like. For instance, the DataTable class has a Columns property that is a collection of DataColumn objects and a Rows property that is a collection of DataRow objects.
 
thank you for help
I have another problem, conversion. I need help with code below. I need to match an array element to a string, to find the matching character, abc contains the english alfabeth, str2 should mathc the alfabet.thank you, frank.

matching elements:
 foreach (char c in abc)
                {
                    //Console.WriteLine(c.ToString());
                    //charVal = Convert.ToChar(str2[i]);
                    charVal = str2[i];
                    if (charVal == str2[i].ToString()) { Console.WriteLine(c.ToString());}
                }
 
Assuming that str2 is declared as a string, then str2[i] is a char. So in the code in post #4, presumably charValue is declared to be a char. Calling ToString() on a char will return a string. As previously mentioned in your other thread, you can't compare a char to a string.

Why do you keep on converting things to string by calling ToString()? A string is already a string, so there no need to convert it to a string. Console.WriteLine() has an override that takes a char parameter, so there is no need to convert a char to a string. By any chance was JavaScript your first programming language, or are you learning C# and JavaScript at the same time?
 
Assuming that str2 is declared as a string, then str2[i] is a char. So in the code in post #4, presumably charValue is declared to be a char. Calling ToString() on a char will return a string. As previously mentioned in your other thread, you can't compare a char to a string.

Why do you keep on converting things to string by calling ToString()? A string is already a string, so there no need to convert it to a string. Console.WriteLine() has an override that takes a char parameter, so there is no need to convert a char to a string. By any chance was JavaScript your first programming language, or are you learning C# and JavaScript at the same time?
I think it is the best to post the whole code where is more visible the problem.
this is a home work, I am taking a c# programing course.
first prog. language pascal, then I started c++ in London uk but the covid thing killed it, also a bit of python. also I've learned jquery, started javascript with freecodecamp but I had to rearrange my priority order because of this course, so I post the code where I need find a possible color for fence of the asked home number, different from neighbour. here I have the color 'names' in string using the englis alfabeth.
sitreadmin:
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace ConsoleApp2kerites1
{
    class Program
    {
        public class Listofrec
        {
            public string szin { get; set; }
            public string hazszam  {get; set;}
        }
        static void Main(string[] args)
        {
            //--------------------
            //File írás és olvasás
            //--------------------
            int i =0;
            int index1 = 0;
            int index2 = 0;
            int i2 =0;
            int i3 = 0;
            int j =0;
            int k =0;
            //string l;
            Random r = new Random();
            //int genRand = r.Next(1, 59);
            int genRand = r.Next(1, 117);
            string szin = " ";
            string szinlehetoseg = " ";
            string ch = " ";
            string abc ="abcdefghijklmnopqrstuvxyz";
            // Declaration of the array
            string[] str1;
            string[] str2;
            str1 = new string[99];
            str2 = new string[99];
            int paros = 0;
            int paratlan = -1;
            int hszam1 = 0;
            int hszamkert = 0;
            string keritesszin = " ";
            //string adat;
            string name = @"c:\Users\Public\textfiles\kerites.txt";
            Listofrec[] adatok = new Listofrec[99];
            //var adatok = new List<Listofrec>();
            //string line;
            //string str= '9';
            /*string path = @"c:\\Users\\Dell\\Desktop\\c#\\kerites.txt";*/
            StreamReader st = new StreamReader(name, Encoding.Default);

            string s;
            string[] words;
            //string[] kerites;
            //var cls = new Listofrec();
            //adatok[1].hazszam ="0";
            //adatok[1].szin = "b";
            Listofrec[] listak = new Listofrec[99];
             Listofrec list1 = new Listofrec()
            {
                hazszam = "0",
                szin = "b"
            };
            listak[0] = list1;
             char charVal;

            //cls.Add(adatok);

            do
            {
                i = i + 1;
                i2 = i2 + 1;

                s = st.ReadLine();

                // i2 = i2 + 1;
                str1[i] = s;
                //string[] words = s.Split(' ');
                //string[i,] words = s.Split(' ');
                words = s.Split(' ');
                str2[i] = words[2];
                Console.WriteLine("- i " + i + "- " + words[0] + "- " + words[1] + "- " + words[2]);
                Console.WriteLine(" lista " + i + " " + str1[i]);
                //if (words[0]==0) {
                //    paros = paros + 1;
                //}[]
                if (Int32.TryParse(words[0], out j))
                {
                    //paros = paros + 1;

                    if (j == 0)
                    {
                        paros = paros + 2;
                        index1 = index1 + 1;
                        Console.WriteLine(j);
                        Console.WriteLine(" Paros szamok " + paros);
                    }
                    if (j == 1)
                    {
                        paratlan = paratlan + 2;
                        index2 = index2 + 1;
                        /*  if (genRand==index2)
                             {
                                  hszamkert = paratlan;
                                  szin = str2[i];
                                  Console.WriteLine(index2+" A kert haz szam " + hszamkert+szin);

                              }*/
                        Console.WriteLine(index2 + " Paratlan szamok " + paratlan);
                    }
                    // Console.WriteLine(" Az utolso szam paros " + paros);

                }

                else
                {
                    Console.WriteLine("String could not be parsed.");
                }

                /* */
                if (j == 1)
                {
                    //
                    if (i > 1)
                    {
                        if (str2[i] == str2[i - 1])
                        {
                            if (str2[i] != "#" && str2[i] != ":")
                            {
                                k = k + 1;
                                Console.WriteLine(i2 + " A szomszeddal egyezo szin " + str2[i]);
                                //adatok[i].hazszam.Add(str2[i]);
                                //adatok[i].szin.Add(paratlan);


                                if (k < 2)
                                {
                                    hszam1 = paratlan;
                                    szin = str2[i];
                                    Console.WriteLine(" A szomszeddal egyezo hazszam " + hszam1);
                                  
                                    Console.WriteLine(" A szomszeddal egyezo kerites szin " + szin + "  hazszam : " + paratlan);
                                }
                            }
                        }
                        else
                        {
                            //Console.WriteLine(" A kerites szin nem egyezik " + str2[i]);

                        }
                    }
                }
                /*                  */

                if (genRand == paros)
                {
                    hszamkert = paratlan;
                    keritesszin = str2[i];
                    Console.WriteLine(index2 + " A kert hazszam " + hszamkert);
                    Console.WriteLine(index2 + " A kert hazszam keritesszine " + str2[i]);
                    /*  if (str2[i] == str2[i - 1] || str2[i] == str2[i + 1])
                          {
                          ch = str2[i];
                              foreach (char c in abc)
                                  {
                                  if (c != ch)
                                      {
                                          ;
                                      }
                                  }
                          }*/
                    }
                    if (genRand == paratlan)
                    { //paratlan == odd
                        hszamkert = paratlan;
                        //keritesszin = fence color
                        keritesszin = str2[i];
                        Console.WriteLine(index2 + " A kert hazszam " + hszamkert);//asked home number
                        Console.WriteLine(index2 + " A kert hazszam keritesszine " + str2[i]);// the asked home's fence color
                        
                    }
                //.^string testStr = "abc123";
             /*   foreach (char c in abc)
                {
                    //Console.WriteLine(c.ToString());
                    //charVal = Convert.ToChar(str2[i]);
                    charVal = str2[i];
                    if (charVal == str2[i].ToString()) { Console.WriteLine(c.ToString());}
                }*/

            }
            while (!st.EndOfStream);

            Console.WriteLine("- i " + i + "- " + words[0] + "- " + words[1] + "- " + words[2]);
            //All sold site's number
            Console.WriteLine(" Az eladott telkek szama " + i);

            if (Int32.Parse(words[0]) == 0)
                {
                     //last solde site has even number
                     Console.WriteLine(" Az utolso eladott telek paros szamu " + paros);
                }
            else
                {
                //last solde site has odd number
                Console.WriteLine(" Az utolso eladott telek paratlan szamu " + paratlan);
                }
          
            Console.WriteLine(" A kerites szin egyezik az elozovel " + szin + "  hazszam : " + hszam1);
            Console.WriteLine(" A kert hazszam  " + hszamkert);
            if (keritesszin != "#" && keritesszin != ":")
            {
                //keritesszin = fence color
                //fence color
                Console.WriteLine(" A kerites szine " + keritesszin);
            }
            if (keritesszin == "#")
            {
                //fence not painted
                Console.WriteLine("  A keritesnek meg nincs lefestve " + keritesszin);
            }
            if (keritesszin == ":")
            {
                //fence not builded
                Console.WriteLine(" A kerites nem keszult el " + keritesszin);
            }
            //Console.WriteLine(" A kerites szine " + szin);

        }
    }
}
also I would like to ask should I start a new thread In the matter? If yes is it possible to move the whole post in a new thread?thank you, frank.
 

Attachments

  • kerites.txt
    764 bytes · Views: 15
I think it is the best to post the whole code where is more visible the problem.
No it isn't. What's best is to write new code that isolates specifically the part that is at issue and omits everything irrelevant to the problem.
 
Generally speaking, you would only use arrays for internal use in a class. If you want to expose any data outside an object then you should use properties and if you want to expose a list of data then you should use a read-only property of a collection type. That way, the consumer can get the existing collection in order to get, set, add and remove items but they cannot replace the existing collection entirely. E.g.
C#:
public class Person
{
    public string GivenName { get; set; }
    public string FamilyName { get; set; }
    public List<Person> Children { get; } = new List<Person>();
}
Here, the Person class has two basic properties for the person's given and family names and a read-only collection property that contains other Person objects that represent that person's children. You might use that like this:
C#:
// It's OK to use an array here because it is for internal use.
var people = new[]
             {
                 new Person {GivenName = "Peter", FamilyName = "Smith"},
                 new Person {GivenName = "Paul", FamilyName = "Jones"},
                 new Person {GivenName = "Mary", FamilyName = "Williams"}
             };

var peter = people[0];

peter.Children.AddRange(new[]
                        {
                            new Person {GivenName = "John", FamilyName = "Smith"},
                            new Person {GivenName = "Jane", FamilyName = "Smith"}
                        });

foreach (var person in people)
{
    Console.WriteLine($"{person.GivenName} {person.FamilyName}");

    if (person.Children.Any())
    {
        Console.WriteLine("Children:");

        foreach (var child in person.Children)
        {
            Console.WriteLine($"{child.GivenName} {child.FamilyName}");
        }
    }
    else
    {
        Console.WriteLine("No children");
    }
}
In this case, the collection property in the Person class also contains Person objects, but your types can refer to any other types you like. For instance, the DataTable class has a Columns property that is a collection of DataColumn objects and a Rows property that is a collection of DataRow objects.
thank you, lovely.
 
No it isn't. What's best is to write new code that isolates specifically the part that is at issue and omits everything irrelevant to the problem.
thank you for help. I post my new code, finding new problems. first if I want a previous and the next element in a list to a given element, the next makes me problem. index +1 can overrun the last element. this is where I need help. another thing, as I 'ask' a number by random between 1 and 117 and it looks I didn't get always. please run the code to see what I try to describe. thank you, frank.
a part of the code I managed to modify:
/*                  */

                if (genRand == paros)
                {
                    hszamkert = paratlan;
                    keritesszin = str2[i];
                    charVal = str2[i].ToLower().ToCharArray()[0];
                    kszinelozo = str2[i-1].ToLower().ToCharArray()[0];
                    //kszinkov = str2[i+1].ToLower().ToCharArray()[0];
                    //if (!st.EndOfStream) { kszinkov = str2[i + 1].ToLower().ToCharArray()[0]; }
                    Console.WriteLine(index2 + " A kert hazszam " + hszamkert);
                    Console.WriteLine(index2 + " A kert hazszam keritesszine " + str2[i]);
                    /*  if (str2[i] == str2[i - 1] || str2[i] == str2[i + 1])
                          {
                          ch = str2[i];
                              foreach (char c in abc)
                                  {
                                  if (c != ch)
                                      {
                                          ;
                                      }
                                  }
                          }*/
                    }
                    if (genRand == paratlan)
                    { //paratlan == odd
                        hszamkert = paratlan;
                        //keritesszin = fence color
                        keritesszin = str2[i];
                        charVal = str2[i].ToLower().ToCharArray()[0];
                        kszinelozo = str2[i - 1].ToLower().ToCharArray()[0];
                        //if (!st.EndOfStream) { kszinkov = str2[i + 1].ToLower().ToCharArray()[0]; }
                    Console.WriteLine(index2 + " A kert hazszam " + hszamkert);//asked home number
                        Console.WriteLine(index2 + " A kert hazszam keritesszine " + str2[i]);// the asked home's fence color
                        
                    }
            }
            while (!st.EndOfStream);
            // string testStr = "abc123";
            /*  */
            char ch2 = ' ';
            ch2 = charVal;
            Console.WriteLine(" a kerites szin " + charVal);
            Console.WriteLine(" a kerites szin " + kszinelozo);
            Console.WriteLine(" a kerites szin " + kszinkov);
            foreach (char c in abc)
             /*                  */

                if (genRand == paros)
                {
                    hszamkert = paratlan;
                    keritesszin = str2[i];
                    charVal = str2[i].ToLower().ToCharArray()[0];
                    kszinelozo = str2[i-1].ToLower().ToCharArray()[0];
                    //kszinkov = str2[i+1].ToLower().ToCharArray()[0];
                    //if (!st.EndOfStream) { kszinkov = str2[i + 1].ToLower().ToCharArray()[0]; }
                    Console.WriteLine(index2 + " A kert hazszam " + hszamkert);
                    Console.WriteLine(index2 + " A kert hazszam keritesszine " + str2[i]);
                    /*  if (str2[i] == str2[i - 1] || str2[i] == str2[i + 1])
                          {
                          ch = str2[i];
                              foreach (char c in abc)
                                  {
                                  if (c != ch)
                                      {
                                          ;
                                      }
                                  }
                          }*/
                    }
                    if (genRand == paratlan)
                    { //paratlan == odd
                        hszamkert = paratlan;
                        //keritesszin = fence color
                        keritesszin = str2[i];
                        charVal = str2[i].ToLower().ToCharArray()[0];
                        kszinelozo = str2[i - 1].ToLower().ToCharArray()[0];
                        //if (!st.EndOfStream) { kszinkov = str2[i + 1].ToLower().ToCharArray()[0]; }
                    Console.WriteLine(index2 + " A kert hazszam " + hszamkert);//asked home number
                        Console.WriteLine(index2 + " A kert hazszam keritesszine " + str2[i]);// the asked home's fence color
                        
                    }
            }
            while (!st.EndOfStream);
            // string testStr = "abc123";
            /*  */
            char ch2 = ' ';
            ch2 = charVal;
            Console.WriteLine(" a kerites szin " + charVal);
            Console.WriteLine(" a kerites szin " + kszinelozo);
            Console.WriteLine(" a kerites szin " + kszinkov);
            foreach (char c in abc)
            {
                //Console.WriteLine(c.ToString());
                //charVal = Convert.ToChar(str2[i]);
                //charVal = str2[i].ToCharArray()[0];
                if (charVal == c)
                { Console.WriteLine(" a kerites szin " + c + charVal); }
            }
 
thank you for help
unfortunately I have another problem regarding custom type. I declared
declaration of custom type:
 Listofrec[] oldal0 = new Listofrec[98];
            
            Listofrec oldal1 = new Listofrec()
            {
                hazszam = 0,
                szin = " "
            };
            oldal0[0] = oldal1;
I try to fill up in loop
fill up in loop:
                    i2 = i2 + 1;
                    oldal1[i2].szin = str2[i2];
                    oldal1[i2].hazszam = paros;
display
display:
 for (int d =0; d<98; d++)
            {

                Console.WriteLine(" a kerites szin " + oldal1[d].szin);
                Console.WriteLine(" a kerites szin " + oldal1[d].szin);
              
           }
I tried to find solution on the net but no luck, please help me, thank you.
 
oldal0 is your array. Your loop above to print things out is trying to access oldal1, a single instance.
 
Last edited:
And then once you fix that, assuming that your ListofRec type is still a class (rather than a struct), then you will have an issue where every array element is pointing to the same single instance.
 
Back
Top Bottom