Thursday, April 23, 2020

Collections in C#

For many applications, you want to create and manage groups of related objects. There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.

Arrays (C# Programming Guide)
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/


Collections   (C# Programming Guide)
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/collections

Simple collection example
// Create a list of strings. var salmons = new List<string>(); salmons.Add("chinook"); salmons.Add("coho"); salmons.Add("pink"); salmons.Add("sockeye");
// Iterate through the list. foreach (var salmon in salmons) { Console.Write(salmon + " "); } // Output: chinook coho pink sockeye


 Sample of Galaxy class that is used by the List<T> is defined in the code.
private static void IterateThroughList()
{
    var theGalaxies = new List<Galaxy>
        {
            new Galaxy() { Name="Tadpole", MegaLightYears=400},
            new Galaxy() { Name="Pinwheel", MegaLightYears=25},
            new Galaxy() { Name="Milky Way", MegaLightYears=0},
            new Galaxy() { Name="Andromeda", MegaLightYears=3}
        };

    foreach (Galaxy theGalaxy in theGalaxies)
    {
        Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);
    }

    // Output:
    //  Tadpole  400
    //  Pinwheel  25
    //  Milky Way  0
    //  Andromeda  3
}

public class Galaxy
{
    public string Name { get; set; }
    public int MegaLightYears { get; set; }
}

No comments:

Post a Comment

LIveCharts2: Charts for Windows and web

Charts for Windows and web including .Net MAUI  LiveCharts - LiveCharts2 (lvcharts.com)