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)

Collections   (C# Programming Guide)

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

UIWebView Deprecation and Xamarin.Forms

Apple started sending following warning messages about UIWebView deprecation. ITMS-90809: Deprecated API Usage - App updates that use UIWeb...