Search code examples
c#arraysgeneric-list

Array in generic List


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.

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>()}");
    }
}

Solution

  • 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"