'What is best practice to store a list of an object within another object

I have an object called product and an object called products.

class product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class products
{
    public List<product> product { get; set; }
}

In the objects products property product i want to store multiple products. This i how i did it in a small prototype solution:

    static void Main(string[] args)
    {
        products productlist = new products();
        List<product> listofproduct = new List<product>();

        for (int i = 0; i < 10; i++)
        {
            product p = new product();
            p.Id = i;
            p.Name = "product with id = " + i.ToString();

            listofproduct.Add(p);
        }

        productlist.product = listofproduct;

        foreach (product prod in productlist.product)
        {
            Console.WriteLine(prod.Name);
        }

        Console.ReadKey();
    }
}

Is this a good way to solve this? Or do you do it in another way in object oriented programming?



Solution 1:[1]

If you don't want to use LINQ and keep your current structure, you could eliminate the need to create full instances in your loop, and the need for listofproduct.

for (int i = 0; i < 10; i++) {
    productlist.product.Add(new product {
        p.Id = i;
        p.Name = "product with id = " + i.ToString();
    });
}

However, the best practice for writing code should be:

What is the easiest way for me to maintain and understand this code?

So if the way you wrote the code in your question is what makes you feel comfortable, then by all means do it. However, I strongly recommend you follow the conventions laid out by MSDN for Capitalization Conventions.

Solution 2:[2]

struct Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    
    public Product(int id, string name)
    {
        this.Id=id;
        this.Name=name;
    }
    public void WriteInfo()
    {
        Console.WriteLine("Id: {0}", Id); 
        Console.WriteLine("Name: {0}", Name);
    }
}

static void Main(string[] args)
{
    var productList=new LinkedList<Product>;
    productList.AddLast(new Product(1,Apple));
    productList.AddLast(new Product(2,Banana));
    
    foreach(var product in productList)
    {
        product.WriteInfo();
    }
}

Solution 3:[3]

If you have enabled ssh for your account then it is due to same reason. I also faced it and with below command you can easily avoid hang problem during clone.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Kennedy
Solution 2 Deantwo
Solution 3