Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Structs con Otras Estructuras de Datos | Structs y Enumeradores
C# Más Allá de lo Básico

bookStructs con Otras Estructuras de Datos

Dado que las estructuras son esencialmente tipos de datos, también puedes utilizarlas para crear Arrays y Listas:

index.cs

index.cs

copy
1234567891011121314151617181920
using System; using System.Collections.Generic; struct Student { public string name; public int age; } class Program { static void Main() { // An array of 50 students Student[] studentsArr = new Student[50]; // A list of students List<Student> studentsList; } }

En una Lista o un Array, se accedería al campo de un objeto Student utilizando la siguiente sintaxis:

index.cs

index.cs

copy
1
variableName[index].fieldName

Por ejemplo:

index.cs

index.cs

copy
1234567
// Array studentsArr[17].name = "Alex"; // List studentsList[27].age = 21; // Note: Both have the same syntax.

También es posible recorrer estos arreglos o listas para asignar o acceder a los datos. Por ejemplo, el siguiente código recorre una List de objetos Students y calcula la edad promedio:

index.cs

index.cs

copy
12345678910111213141516171819202122232425262728293031323334353637
using System; using System.Collections.Generic; struct Student { public string name; public int age; } class Program { static void Main() { // Creating an array Student[] students = new Student[7]; // Setting some data students[0].age = 18; students[1].age = 13; students[2].age = 16; students[3].age = 21; students[4].age = 30; students[5].age = 36; students[6].age = 20; int totalAge = 0; for (int i = 0; i < students.Length; i++) { totalAge += students[i].age; } // Formula for average is "sum of elements / number of elements" float averageAge = totalAge / students.Length; Console.WriteLine($"Average Age: {averageAge}"); } }

Es evidente que aquí la estructura Student funciona como un tipo de dato. También podemos utilizar Student como valor en un diccionario. A continuación se muestra un ejemplo de cómo usar una Struct como valor en un diccionario:

index.cs

index.cs

copy
123456789101112131415161718192021222324
using System; using System.Collections.Generic; struct Student { public string name; public int age; } class Program { static void Main() { var studentsByID = new Dictionary<int, Student>(); Student student; student.name = "Thomas"; student.age = 36; studentsByID.Add(0, student); Console.WriteLine(studentsByID[0].name); } }
question mark

¿Cuál es la sintaxis correcta para acceder al atributo score del primer jugador?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 4

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Suggested prompts:

Can you show me an example of how to use a struct as a value in a dictionary?

How do I access or modify a struct stored in a dictionary?

What are some best practices for using structs in collections like arrays, lists, or dictionaries?

Awesome!

Completion rate improved to 2.04

bookStructs con Otras Estructuras de Datos

Desliza para mostrar el menú

Dado que las estructuras son esencialmente tipos de datos, también puedes utilizarlas para crear Arrays y Listas:

index.cs

index.cs

copy
1234567891011121314151617181920
using System; using System.Collections.Generic; struct Student { public string name; public int age; } class Program { static void Main() { // An array of 50 students Student[] studentsArr = new Student[50]; // A list of students List<Student> studentsList; } }

En una Lista o un Array, se accedería al campo de un objeto Student utilizando la siguiente sintaxis:

index.cs

index.cs

copy
1
variableName[index].fieldName

Por ejemplo:

index.cs

index.cs

copy
1234567
// Array studentsArr[17].name = "Alex"; // List studentsList[27].age = 21; // Note: Both have the same syntax.

También es posible recorrer estos arreglos o listas para asignar o acceder a los datos. Por ejemplo, el siguiente código recorre una List de objetos Students y calcula la edad promedio:

index.cs

index.cs

copy
12345678910111213141516171819202122232425262728293031323334353637
using System; using System.Collections.Generic; struct Student { public string name; public int age; } class Program { static void Main() { // Creating an array Student[] students = new Student[7]; // Setting some data students[0].age = 18; students[1].age = 13; students[2].age = 16; students[3].age = 21; students[4].age = 30; students[5].age = 36; students[6].age = 20; int totalAge = 0; for (int i = 0; i < students.Length; i++) { totalAge += students[i].age; } // Formula for average is "sum of elements / number of elements" float averageAge = totalAge / students.Length; Console.WriteLine($"Average Age: {averageAge}"); } }

Es evidente que aquí la estructura Student funciona como un tipo de dato. También podemos utilizar Student como valor en un diccionario. A continuación se muestra un ejemplo de cómo usar una Struct como valor en un diccionario:

index.cs

index.cs

copy
123456789101112131415161718192021222324
using System; using System.Collections.Generic; struct Student { public string name; public int age; } class Program { static void Main() { var studentsByID = new Dictionary<int, Student>(); Student student; student.name = "Thomas"; student.age = 36; studentsByID.Add(0, student); Console.WriteLine(studentsByID[0].name); } }
question mark

¿Cuál es la sintaxis correcta para acceder al atributo score del primer jugador?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 4
some-alt