El antes y el después de LINQ

Problema: a partir de una lista de objetos de tipo “Coche”, quiero sumar el precio de cada uno de ellos agrupado por marca.
La clase coche tiene la siguiente forma
public class Coche
{
  public int IdCoche { get; set; }
  public string Matricula { get; set; }
  public int IdMarca { get; set; }
  public int NumeroPuertas { get; set; }
  public int Precio { get; set; }
  public Coche(int idCoche, string matricula, int idMarca, int numeroPuertas, int precio)
  {
     this.IdCoche = idCoche;
     this.Matricula = matricula;
     this.IdMarca = idMarca;
     this.NumeroPuertas = numeroPuertas;
     this.Precio = precio;
   }
}
Inicializamos una lista con objetos de la clase  Coche
List<Coche> lista = new List<Coche>();
lista.Add(new Coche(1, “3322-AAA”, 1, 3, 15000));
lista.Add(new Coche(2, “3322-EEE”, 2, 5, 25000));
lista.Add(new Coche(3, “3322-III”, 3, 3, 35000));
lista.Add(new Coche(4, “3322-OOO”, 1, 3, 18000));
lista.Add(new Coche(5, “3322-UUU”, 2, 5, 20000));
lista.Add(new Coche(6, “1111-AAA”, 3, 3, 150000));
lista.Add(new Coche(7, “1111-EEE”, 1, 3, 30000));
lista.Add(new Coche(8, “1111-III”, 1, 5, 28000));
lista.Add(new Coche(9, “1111-OOO”, 3, 5, 16000));
lista.Add(new Coche(10, “1111-UUU”, 1, 5, 9000));
Solución antes de LINQ (una de muchas)
Hashtable hash = new Hashtable();
foreach (Coche c in lista)
{
  if (!hash.ContainsKey(c.IdMarca))
  {
    hash.Add(c.IdMarca, c.Precio);
  }
  else
  {
    hash[c.IdMarca] = (int)hash[c.IdMarca] + c.Precio;
  }
}
IDictionaryEnumerator _enumerator = hash.GetEnumerator();
while (_enumerator.MoveNext())
{
  Console.WriteLine(String.Format(“Marca: {0}, Total Precio: {1}”, _enumerator.Key, _enumerator.Value));
}
Solución después de LINQ
var marcas = from m in lista
             group m by m.IdMarca into g
             select new { IdMarca = g.Key , TotalPorMarca = g.Sum (m => m.Precio) };
foreach (var marca in marcas)
{
  Console.WriteLine(String.Format(“Marca: {0}, Total Precio: {1}”, marca.IdMarca, marca.TotalPorMarca));
}
Resultado
Marca: 1, Total Precio: 100000
Marca: 2, Total Precio: 45000
Marca: 3, Total Precio: 201000
Saludos.

One thought on “El antes y el después de LINQ”

  1. El mismo resultado utilizando sintaxis de métodos.
    lista.GroupBy(coche => coche.IdMarca)
    .Select(grupo => new { IdMarca= grupo.Key , TotalPorMarca = grupo.Sum(grupoSum => grupoSum.Precio)}).ToList()
    .ForEach(item => Response.Write(String.Format(“Marca: {0}, Total Precio: {1}”, item.IdMarca, item.TotalPorMarca)));
    Salu2! 😉

Leave a Reply to Guillermo Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.