c# array in generic list

1736 views c#
2

I need to create a Generic List and keep the data in the Array class. Array will be as much as I mentioned in the constructor method. (I'm open to more practical solutions and ideas) My problem is that I don't get int values when I print in the List, and I can't find out how to access that data one by one.

Regards

         public class Demo
    {
        public int GrupKodu { get; set; }
        public string GrupAd { get; set; }
        public int[] Notlar;

        public Demo(int GrupKodu, string GrupAd, int NotAdet , int[] a  )
        {
            this.GrupKodu = GrupKodu;
            this.GrupAd = GrupAd;
            this.Notlar = new int[NotAdet];
            this.Notlar = a;
        }

        public override string ToString()
        {
            return $"Grup Kodu : {this.GrupKodu} Grup Ad? : {this.GrupAd} Notlar : {Notlar}";
        }
    }

I'm doing an invocation with data insertion and for loop. I tried the same print operation with the Foreach Loop, but the Sonush did not change.

    static void Main(string[] args)
    {
        List<Demo> DemoListe = new List<Demo>();
        DemoListe.Add(new Demo(101, "umt", 6, new int[] { 1, 2, 3, 4, 5, 6 }));
        DemoListe.Add(new Demo(101, "umt", 2, new int[] { 1, 2,}));
        DemoListe.Add(new Demo(101, "umt", 3, new int[] { 1, 2, 3}));
        DemoListe.Add(new Demo(101, "umt", 7, new int[] { 1, 2, 3, 4, 5, 6,7 }));
        DemoListe.Add(new Demo(101, "umt", 8, new int[] { 1, 2, 3, 4, 5, 6 ,7,8}));

        foreach (Demo item in DemoListe)
        {
            Console.WriteLine(item.ToString());
        }

        for (int i = 0; i < DemoListe.Count(); i++)
        {
            Console.WriteLine($"GrupAd : {DemoListe[i].GrupAd}  GrupKod : {DemoListe[i].GrupKodu}  Notlar : {DemoListe[i].Notlar.ToArray<int>()}");
        }
    }

answered question

1 Answer

3

You could use String.Join in your ToString override like so:

public override string ToString()
{
    return $"Grup Kodu : {this.GrupKodu} Grup Ad? : {this.GrupAd} Notlar : {String.Join(", ", Notlar)}";
}

String.Join turns an enumerable into a string seperated by a seperator.

So if Notlar = [1,2,3], String.Join(", ", Notlar) = "1, 2, 3"

posted this

Have an answer?

JD

Please login first before posting an answer.