Skip to content

Instantly share code, notes, and snippets.

@brunossn
Last active June 20, 2024 18:55
Show Gist options
  • Save brunossn/1f2a4ca9167b49cabc58d8e90e8e923b to your computer and use it in GitHub Desktop.
Save brunossn/1f2a4ca9167b49cabc58d8e90e8e923b to your computer and use it in GitHub Desktop.
C# Extensions to update ObservableCollection itens without remove and reinsert.
public static class ObservableCollectionHelpers
{
public static void Replace<T>(this ObservableCollection<T> collection, IEnumerable<T> novosItens)
{
ArgumentNullException.ThrowIfNull(collection);
ArgumentNullException.ThrowIfNull(novosItens);
var numeroColunasColecao = collection.Count;
var numeroColunasNovosItens = novosItens.Count();
for ( var i = 0; i < numeroColunasNovosItens; i++)
{
if (i < numeroColunasColecao)
collection[i] = novosItens.ElementAt(i);
else
collection.Add(novosItens.ElementAt(i));
}
for (var i = numeroColunasColecao - 1; i >= numeroColunasNovosItens; i--)
collection.RemoveAt(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment