LINQ UNION-ADDRANGE DIFFERENCE – DIFERENCIA

Autor: Matías Creimerman

2012-06-05

"LINQ UNION-ADDRANGE DIFFERENCE – DIFERENCIA"

Hoy me preguntaron si no era lo mismo hacer un AddRange en una colección que un Union de LINQ y claramente la respuesta es NO!.

Por qué no es lo mismo hacer un AddRange que hacer un Union y asignar a la misma colección?

Porque el AddRange repite información en cambio el Union no agrega datos repetidos (salvo que sean instancias distintas con colecciones de objetos).

Today a developer asked me if using AddRange over a collection was the same that using LINQ’s UNION, and as a matter of fact the answer was “NO!”.

Why is not the same to do AddRange or to do Union and assign to same collection?

Because the AddRange repeats information, on the other hand, UNION does not add repeated data (unless they are different instances with object collections).

Veamos código (Let’s check out code)…
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“*******************************”);
Console.WriteLine(“Probando Union y AddRange”);
Console.WriteLine(“*******************************”);
Console.WriteLine(“Agrego a la lista nros del 1 al 10”);
List list = GetNewList(0, 10);
Console.WriteLine(“Creo otra lista de nros del 1 al 10”);
List list2 = GetNewList(0, 10);
Console.WriteLine(“Hago un Union y muestro”);
list = list.Union(list2).ToList();
foreach (var l in list)
{
Console.WriteLine(“Nro: {0}”, l);
}
Console.WriteLine(“Reinicio listas, hago AddRange y muestro”);
list = GetNewList(0, 10);
list.AddRange(list2);
foreach (var l in list)
{
Console.WriteLine(“Nro: {0}”, l);
}
Console.ReadKey();
}
static List GetNewList(int baseNumber, int length)
{
List rv = new List();
for (int i = baseNumber; i < length; i++)
{
rv.Add(i);
}
return rv;
}
}

LINQ ADDRANGE

This content is property of Matias Creimerman.
Any misuse of this material will be punishable.
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.