Insectos + persistencia - Ejercicio de Programacion C# Sharp

En este ejercicio, debes crear una nueva versión del ejercicio de los insectos, donde se persistan los datos utilizando algún tipo de almacenamiento, como una base de datos o un sistema de archivos. El objetivo es aprender a manejar la persistencia de datos en C# a través de bases de datos o archivos. Para lograr esto, deberás implementar un mecanismo para almacenar y recuperar la información relacionada con los insectos, lo que permitirá que los datos persistan incluso después de que el programa se cierre. Este ejercicio te ayudará a comprender cómo interactuar con bases de datos o el sistema de archivos para guardar información, lo cual es una habilidad esencial en el desarrollo de aplicaciones que requieren gestionar grandes volúmenes de datos o mantener registros a largo plazo.

Al implementar la persistencia de los datos en el ejercicio de los insectos, aprenderás a crear tablas o archivos para almacenar los datos, así como a realizar operaciones de lectura y escritura en ellos. Además, explorarás cómo gestionar el ciclo de vida de los datos en una aplicación, desde la creación y almacenamiento hasta la recuperación y actualización.

 Categoría

Persistencia de Objetos

 Ejercicio

Insectos + Persistencia

 Objectivo

Crear una nueva versión del ejercicio "insectos" (17 de abril), que debe guardar sus datos utilizando la persistencia.

 Ejemplo Ejercicio C#

 Copiar Código C#
// Importing necessary namespaces for file I/O operations and general functionality
using System; // To use general .NET functionalities
using System.Collections.Generic; // To use List for storing insect objects
using System.IO; // To perform file I/O operations

// Define a class to represent an Insect
class Insect
{
    public string Name { get; set; } // Name of the insect
    public string Color { get; set; } // Color of the insect
    public double WingSpan { get; set; } // Wing span of the insect (in centimeters)
    
    // Constructor to initialize the insect's properties
    public Insect(string name, string color, double wingSpan)
    {
        Name = name; // Assign name to the insect
        Color = color; // Assign color to the insect
        WingSpan = wingSpan; // Assign wing span to the insect
    }
    
    // Method to represent the insect as a string (for easy display and storage)
    public override string ToString()
    {
        return $"{Name},{Color},{WingSpan}"; // Return insect data as a comma-separated string
    }
}

// Define a class to handle the persistence (save/load) of Insect data to/from a file
class InsectDataPersistence
{
    private const string FilePath = "insects_data.txt"; // File path for storing insect data

    // Method to save a list of insects to a file
    public void SaveInsectsToFile(List insects)
    {
        try
        {
            // Open the file for writing (it will overwrite any existing data)
            using (StreamWriter writer = new StreamWriter(FilePath, false))
            {
                // Write each insect's data as a new line in the file
                foreach (var insect in insects)
                {
                    writer.WriteLine(insect.ToString()); // Save the insect as a string
                }
            }
            // Notify that the data has been saved successfully
            Console.WriteLine("Insect data has been saved to the file.");
        }
        catch (Exception ex)
        {
            // Display an error message if something goes wrong
            Console.WriteLine($"Error saving insect data to file: {ex.Message}");
        }
    }

    // Method to load a list of insects from a file
    public List LoadInsectsFromFile()
    {
        List insects = new List(); // List to store the loaded insects

        try
        {
            // Open the file for reading
            using (StreamReader reader = new StreamReader(FilePath))
            {
                string line;
                // Read each line of the file
                while ((line = reader.ReadLine()) != null)
                {
                    // Split the line into parts (name, color, wing span)
                    var parts = line.Split(',');

                    // Create a new Insect object and add it to the list
                    insects.Add(new Insect(parts[0], parts[1], double.Parse(parts[2])));
                }
            }
            // Notify that the data has been loaded successfully
            Console.WriteLine("Insect data has been loaded from the file.");
        }
        catch (Exception ex)
        {
            // Display an error message if something goes wrong
            Console.WriteLine($"Error loading insect data from file: {ex.Message}");
        }

        return insects; // Return the list of loaded insects
    }
}

// Main class to demonstrate the insect data persistence functionality
class Program
{
    static void Main(string[] args)
    {
        // Create a list of insects with sample data
        List insects = new List
        {
            new Insect("Dragonfly", "Green", 15.5),
            new Insect("Butterfly", "Yellow", 10.2),
            new Insect("Bee", "Black and Yellow", 3.1)
        };

        // Create an instance of InsectDataPersistence to handle file operations
        InsectDataPersistence persistence = new InsectDataPersistence();

        // Save the insect data to the file
        persistence.SaveInsectsToFile(insects);

        // Load the insect data from the file
        List loadedInsects = persistence.LoadInsectsFromFile();

        // Display the loaded insects' data
        Console.WriteLine("\nLoaded Insects:");
        foreach (var insect in loadedInsects)
        {
            Console.WriteLine($"Name: {insect.Name}, Color: {insect.Color}, Wing Span: {insect.WingSpan} cm");
        }
    }
}

 Salida

Insect data has been saved to the file.
Insect data has been loaded from the file.

Loaded Insects:
Name: Dragonfly, Color: Green, Wing Span: 15.5 cm
Name: Butterfly, Color: Yellow, Wing Span: 10.2 cm
Name: Bee, Color: Black and Yellow, Wing Span: 3.1 cm

 Comparte este Ejercicio C# Sharp

 Más Ejercicios de Programacion C# Sharp de Persistencia de Objetos

¡Explora nuestro conjunto de ejercicios de programación C# Sharp! Estos ejercicios, diseñados específicamente para principiantes, te ayudarán a desarrollar una sólida comprensión de los conceptos básicos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte de manera gradual a medida que adquieres confianza en la codificación en C#.

  •  Ciudades - persistencia

    En este ejercicio, deberás crear una nueva versión de la base de datos de ciudades, utilizando persistencia para almacenar sus datos en lugar de archivos de texto. El...

  •  Tabla + matriz + archivos

    En este ejercicio, se te pide que amplíes el ejercicio anterior (tablas + array) añadiendo dos nuevos métodos. El primero de estos métodos debe encargarse de volcar l...

  •  Tabla + SetOfTables + archivos

    En este ejercicio, deberás expandir el ejercicio anterior (tablas + array + archivos) creando tres nuevas clases: Table, SetOfTables...