IndexedObservableCollection.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System; 6 using System.Collections.Generic; 7 using System.Collections.ObjectModel; 8 using System.Linq; 9 using System.Text; 10 using System.Threading.Tasks; 11 12 namespace Microsoft.PowerToys.Settings.UI.Helpers 13 { 14 #pragma warning disable SA1649 // File name should match first type name 15 public class IndexedItem<T> 16 #pragma warning restore SA1649 // File name should match first type name 17 { 18 public T Item { get; set; } 19 20 public int Index { get; set; } 21 22 public IndexedItem(T item, int index) 23 { 24 Item = item; 25 Index = index; 26 } 27 } 28 29 #pragma warning disable SA1402 // File may only contain a single type 30 public partial class IndexedObservableCollection<T> : ObservableCollection<IndexedItem<T>> 31 #pragma warning restore SA1402 // File may only contain a single type 32 { 33 public IndexedObservableCollection(IEnumerable<T> items) 34 { 35 int index = 0; 36 foreach (var item in items) 37 { 38 Add(new IndexedItem<T>(item, index++)); 39 } 40 } 41 42 public IEnumerable<T> ToEnumerable() 43 { 44 return this.Select(x => x.Item); 45 } 46 47 public void Swap(int index1, int index2) 48 { 49 var temp = this[index1]; 50 this[index1] = this[index2]; 51 this[index2] = temp; 52 53 // Update the original index of the items 54 this[index1].Index = index1; 55 this[index2].Index = index2; 56 } 57 } 58 }