Last active
June 20, 2024 18:55
-
-
Save brunossn/1f2a4ca9167b49cabc58d8e90e8e923b to your computer and use it in GitHub Desktop.
C# Extensions to update ObservableCollection itens without remove and reinsert.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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