Good day community, there is a common scenario and I haven't seen any similar questions, so I'll share the solution right away.
Basically, we have a list of items and we want to update a particular property using Linq
.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("¡Saludos Hermandad de SOes!");
List<Movil> lista = new List<Movil>(){
new Movil(){
Id = 1, Marca = "iPhone", Conexion = "LTE"},
new Movil(){
Id = 2, Marca = "Samsung", Conexion = "4G"},
new Movil(){
Id = 3, Marca = "Xiaomi", Conexion = "4G"}
};
Console.WriteLine("Seleccionar todos los 4G");
var listaFiltrada = lista.Where(elemento=>elemento.Conexion.Equals("4G", StringComparison.InvariantCultureIgnoreCase));
foreach(var item in listaFiltrada){
Console.WriteLine("{0} - {1} - {2}", item.Id, item.Marca, item.Conexion);
}
Console.WriteLine("Actualizando de 4G a LTE");
//Aqui quiero hacer uso de Linq en vez de usar un bucle for, foreach
}
public class Movil{
public int Id {get;set;}
public string Marca {get;set;}
public string Conexion {get;set;}
}
}
In some cases it may be necessary to use an
.ToList()
afteruse.Select()
, this allows the to.Select()
be evaluated and the update applied.If you're using a list like in this example, everything looks fresh.
In case you want to update several properties: