// Vamos a crear una lista de alumnos
// Vamos a añadir 10 alumnos de la siguiente manera:
// «Alumno 1», «Alumno 2″,…,»Alumno 10″
// Vamos a borrar el alumno que esté en la posición 5
// Vamos a crear una función que nos diga si algún alumno
// tiene como subcadena la cadena que le pasemos
// existeSubcadena(alumnos,»7»)->true porque hay un «Alumno 7″
// existeSubcadena(alumnos,»27»)->false porque no subcadena «27»
Categoría: C#
Ejemplos Arrays
int[] numeros;
// También se puede definir e inicializar en una sola línea
String[] numeros2 = new String[5];
foreach(String num in numeros2) {
Console.WriteLine(num);
}
String[] alumnos = { "ana", "pep", "iu" };
foreach (String alumno in alumnos)
{
Console.WriteLine(alumno);
}
for(int i = 0; i < alumnos.Length; i++)
{
Console.WriteLine("El alumno "+i+" es " + alumnos[i]);
}
alumnos[1] = "Pepito grillo";
for (int i = 0; i < alumnos.Length; i++)
{
Console.WriteLine("El alumno " + i + " es " + alumnos[i]);
}
int[,] matriz = { { 1, 2, 3 }, { 4, 5, 6}, { 7, 8, 9 } };
foreach (int num in matriz)
{
Console.WriteLine(num);
}
for(int i = 0; i < matriz.GetLength(0); i++)
{
for(int j = 0; j < matriz.GetLength(1); j++)
{
Console.Write(matriz[i, j]+" ");
}
Console.WriteLine("");
}
int[][] matriz2 = new int[2][];
matriz2[0] =new int[]{ 1,2};
matriz2[1]= new int[] { 1, 2,4,4,5,6,6 };
String[] frase = { "hola", "que", "tal", "Estamos" };
Console.WriteLine(String.Join(",",frase));
Array.Sort(frase);
Console.WriteLine(String.Join(",", frase));
Array.Reverse(frase);
Console.WriteLine(String.Join(",", frase));
Soluciones cadenas
static String arbolito(int n)
{
// Dibuja por consola un arbolito de asteriscos
// arbolito(3)
// *1
// **2
// ***3
// Divide y vencerás
String res = "";
String cad = "";
for(int i = 1; i <= n; i++)
{
cad += "*";
res += cad + "\n";
}
return res;
}
static int contarLetra(String cadena, String letra)
{
cadena=cadena.ToLower();
letra=letra.ToLower();
// no devuelve el número de veces que letra aparece en cadena
// contarLetra("Hola amigo","o")->2
int cont = 0;
for(int i=0;i< cadena.Length; i++)
{
if (cadena.Substring(i, 1)== letra){
cont++;
}
}
return cont;
}
static int contarLetraIndex(String cadena, String letra)
{
cadena = cadena.ToLower();
letra = letra.ToLower();
// no devuelve el número de veces que letra aparece en cadena
// contarLetra("Hola amigo","o")->2
int cont = 0;
int pos=cadena.IndexOf(letra);
while (pos != -1)
{
cont++;
pos = cadena.IndexOf(letra, pos + 1);
}
return cont;
}
Ejercicios cadenas
static void arbolito(int n)
{
// Dibuja por consola un arbolito de asteriscos
// arbolito(3)
// *
// **
// ***
}
static int contarLetra(String cadena, String letra)
{
// no devuelve el número de veces que letra aparece en cadena
// contarLetra("Hola amigo","o")->2
}
Ejercicios para mañana
10 trucos para refactorizar código de C#
Cambiar borrado de registros
En .NET por defecto se eliminan los registros relacionados en cascada. Para evitarlo antes de actualizar la base de datos tenemos que cambiar la migración:
constraints: table =>
{
table.PrimaryKey("PK_ProfesionalesActividades", x => x.Id);
table.ForeignKey(
name: "FK_ProfesionalesActividades_Actividad_ActividadId",
column: x => x.ActividadId,
principalTable: "Actividad",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProfesionalesActividades_Profesionales_ProfesionalId",
column: x => x.ProfesionalId,
principalTable: "Profesionales",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
Para que por defecto sea así en todas las relaciones lo tenemos que poner en el contexto:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var foreignKey in modelBuilder.Model.GetEntityTypes()
.SelectMany(e => e.GetForeignKeys()))
{
foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
}
}
Y si la cosa ya está hecha añadimos una migración a mano:
In the Package Manager Console, create a new, empty migration with the Add-Migration command, then fill in the Up method like this:
migrationBuilder.DropForeignKey(
name: "FK_ElementsPerStrip_Strips_StripId",
table: "ElementsPerStrip");
migrationBuilder.AddForeignKey(
name: "FK_ElementsPerStrip_Strips_StripId",
table: "ElementsPerStrip",
column: "StripId",
principalTable: "Strips",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
For completeness, do the opposite in the Down method:
migrationBuilder.DropForeignKey(
name: "FK_ElementsPerStrip_Strips_StripId",
table: "ElementsPerStrip");
migrationBuilder.AddForeignKey(
name: "FK_ElementsPerStrip_Strips_StripId",
table: "ElementsPerStrip",
column: "StripId",
principalTable: "Strips",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
Evitar ciclos en la API
builder.Services.AddControllers().AddJsonOptions(x =>
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
o
[JsonIgnore]
Deshabilitar CORS
using Microsoft.EntityFrameworkCore;
using Profesiones.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<Contexto>(options =>
options.UseSqlServer("Server=.\\SQLExpress;Database=Profesiones;Trusted_Connection=True;"));
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();




