Answers for "c# list reference"

C#
1

List c#

using System;
using System.Collections.Generic;
using System.Linq;

public class ListExample
{
  static List<Animals> animalsList = new List<Animals>();

  class Animals //You can use "class" or "struct"
  {
    public string animalName;
    public int animalCount;
  }

  public static void Main()
  {
    animalsList.Clear(); //This method clears the animals list

    animalsList.Add(CreateAnimal("Elephant", 5)); //Add a new element to the list
    animalsList.Add(CreateAnimal("Monkey", 18));  //Add a new element to the list
    animalsList.Add(CreateAnimal("Pig", 20));     //Add a new element to the list
    animalsList.Add(CreateAnimal("Cow", 4));      //Add a new element to the list

    for (int i = 0; i < animalsList.Count(); i++)
    {
      Console.WriteLine("There are " + animalsList[i].animalCount + " " + animalsList[i].animalName);
      //Console output:
      //There are 5 Elephant
      //There are 18 Monkey
      //There are 20 Pig
      //There are 4 Cow
    }
  }

  static Animals CreateAnimal(string name, int count) //A simple animal element setup method
  {
    Animals newAnimal = new Animals();
    newAnimal.animalName = name;   //Set animal name
    newAnimal.animalCount = count; //Set animals count

    return newAnimal;
  }
}
Posted by: Guest on October-14-2021

Code answers related to "c# list reference"

C# Answers by Framework

Browse Popular Code Answers by Language