I am looking for a collection where no element can exist more than once, and are also indexed. Similar to Dictionary, but without Key, just Value. Similar to a HashSet, but indexed so I can easily retrieve an element without iterating over the collection. I hope this makes sense. :)
You can use a HashSet. It is "indexed", after all, performance would be lacking if it weren't.
Use the Contains method to "retrieve" an element. If you want to remove it as well, use Remove.
Both methods are O(1) operations.
You can use a Dictionary<T, T> for that and insert elements using Add(value, value).
However, that only makes sense if your type properly implements Equals(object) and GetHashCode(). If it doesn't, two different instanced will never be equal and the HashSet<T>'s Contains(T) method already tells you whether you have the element reference of nor.
HashSet class is best for your work. I won't allow duplicate entries.
Note that the HashSet.Add(T item) method returns a bool -- true if the item was added to the collection; false if the item was already present.
Simply you can add an Extension method to throw exception as
public static void AddOrThrow<T>(this HashSet<T> hash, T item)
{
if (!hash.Add(item))
throw new ValueExistingException();
}
The easiest way to do this is make a class that implements IList<T> but uses a List<T> and HashSet<T> internally. You then just have each method act on each collection as needed.
using System;
using System.Collections.Generic;
namespace Example
{
public class UniqueList<T> : IList<T>
{
private readonly List<T> _list;
private readonly HashSet<T> _hashset;
public UniqueList()
{
_list = new List<T>();
_hashset = new HashSet<T>();
}
public UniqueList(IEqualityComparer<T> comparer)
{
_list = new List<T>();
_hashset = new HashSet<T>(comparer);
}
void ICollection<T>.Add(T item)
{
Add(item);
}
public bool Add(T item)
{
var added = _hashset.Add(item);
if (added)
{
_list.Add(item);
}
return added;
}
public void RemoveAt(int index)
{
_hashset.Remove(_list[index]);
_list.RemoveAt(index);
}
public T this[int index]
{
get { return _list[index]; }
set
{
var oldItem = _list[index];
_hashset.Remove(oldItem);
var added = _hashset.Add(value);
if (added)
{
_list[index] = value;
}
else
{
//Put the old item back before we raise a exception.
_hashset.Add(oldItem);
throw new InvalidOperationException("Object already exists.");
}
}
}
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
void IList<T>.Insert(int index, T item)
{
Insert(index, item);
}
public bool Insert(int index, T item)
{
var added = _hashset.Add(item);
if (added)
{
_list.Insert(index, item);
}
return added;
}
public void Clear()
{
_list.Clear();
_hashset.Clear();
}
public bool Contains(T item)
{
return _hashset.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
var removed = _hashset.Remove(item);
if (removed)
{
_list.Remove(item);
}
return removed;
}
public int Count
{
get { return _list.Count; }
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
I did explicit implementations of Add and Insert so I could give them versions that returned a bool to tell if the operation succeeded or not. I could not return a value in the T this[int index] setter so I have it throw a InvalidOperationException if you attempt to insert a duplicate.
It does not throw if you do ICollection.Add on a duplicate, it just does not add it. This is because that is the behavior HashSet<T>.ICollection<T>.Add has and i wanted to mimic it.
Related
I am looking for a collection that matches the following conditions:
Elements in the collection are never repeated. That is, something ISet<T>-like.
The order of elements in the collection does not change unless elements are removed from the collection. (In my use-case I never remove any elements at all).
I want to be able to get the index of the element I have just added. Due to the requirement 1 that would mean: receiving the index of the element if it already exists in the collection or receiving something like .Count if the element does not exist.
I tried using OrderedSet collection and then getting the index of the element with a one-liner extension method. The problem is it takes around 100ms on my machine every time I try to add a new element in a collection that already consists of couple of thousands. That is a big deal when adding lots of elements into a huge collection.
I suspect that getting the index could be done in the same place where adding the element is. Therefore, I am looking for a probably existing collection for such purpose.
Thank you in advance.
How about:
public class SpecialList<T> : List<T>
{
public new int Add(T Item)
{
if (Contains(Item))
{
return IndexOf(Item);
}
else
{
base.Add(Item);
return Count - 1;
}
}
}
Alright, so considering this problem I tried 4 solutions:
Making an OrderedSet<T> with an AddWithIndex extension method
Making a HashSet<T> with an AddWithIndex extension method. Although it doesn't guarantee the order of the elements it could still be useful in some scenarios.
Extending the List<T> class the way JerryM proposed
Writing my own IndexedSet<T> class
All of the tests were taken on the following piece of code:
static void Main(string[] args)
{
var elements = Enumerable.Range(0, 1000000).Select(i => i.ToString()).ToList();
//Initialize collection here
//...
var sw = new Stopwatch();
sw.Start();
foreach (var element in elements)
{
//Add element to collection here
//...
}
sw.Stop();
Console.WriteLine("Elapsed time: {0}", sw.Elapsed);
}
This test only covers the case where all elements are different and is not really representative when you have lots of repeating elements.
Test 1.
AddWithIndex extension method for HashSet<T> (it is basically the same for OrderedSet<T>):
static class HashSetExtensions
{
public static int AddWithIndex<T>(this HashSet<T> set, T element)
{
if (set.Add(element))
{
return set.Count - 1;
}
return set.IndexOf(element);
}
public static int IndexOf<T>(this HashSet<T> set, T element)
{
int index = 0;
foreach (var item in set)
{
if (element.Equals(item))
{
return index;
}
index++;
}
return -1;
}
}
This gave me 0.3842932 seconds on HashSet<T> and 1.1972123 seconds on OrderedSet<T>.
Test 2.
Deriving from List<T> the way JerryM proposed results in 7.6716346 seconds on a collection of 20000 elements (that is 50 times less elements than in collections used for other tests) and roughly infinite time on the original 1000000 elements.
Test 3.
Finally, I created the following IndexedSet<T> collection which is basically a wrapper on both List<T> and HashSet<T>:
public class IndexedSet<T> : IReadOnlyList<T>, IList<T>
{
private readonly List<T> _list = new List<T>();
private readonly HashSet<T> _set = new HashSet<T>();
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
public int Add(T item)
{
if (_set.Add(item))
{
_list.Add(item);
return _list.Count - 1;
}
return _list.IndexOf(item);
}
void ICollection<T>.Add(T item)
{
Add(item);
}
public void Clear()
{
_list.Clear();
_set.Clear();
}
public bool Contains(T item)
{
return _set.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
bool remove = _set.Remove(item);
if (remove)
_list.Remove(item);
return remove;
}
public int Count => _list.Count;
public bool IsReadOnly => false;
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
public void Insert(int index, T item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
T item = _list[index];
_list.RemoveAt(index);
_set.Remove(item);
}
public T this[int index]
{
get { return _list[index]; }
set
{
T item = _list[index];
_set.Remove(item);
_list[index] = value;
_set.Add(value);
}
}
}
This gave me 0.3558594 seconds (that is even a bit faster than extension for HashSet<T>) and guaranteed the order of the elements (just like OrderedSet<T>).
Hopefully, this would be useful for someone in future.
This question already has answers here:
How to serialize/deserialize a custom collection with additional properties using Json.Net
(6 answers)
Closed 7 years ago.
I created a custom List class that maintains a set of item ids for performance reasons:
public class MyCustomList : List<ItemWithID>
{
private HashSet<int> itemIDs = new HashSet<int>();
public MyCustomList()
{
}
[JsonConstructor]
public MyCustomList(IEnumerable<ItemWithID> collection)
: base(collection)
{
itemIDs = new HashSet<int>(this.Select(i => i.ID));
}
public new void Add(ItemWithID item)
{
base.Add(item);
itemIDs.Add(item.ID);
}
public new bool Remove(ItemWithID item)
{
var removed = base.Remove(item);
if (removed)
{
itemIDs.Remove(item.ID);
}
return removed;
}
public bool ContainsID(int id)
{
return itemIDs.Contains(id);
}
}
I want to deserialize this List from a simply JSON array e.g.:
JsonConvert.DeserializeObject<MyCustomList>("[{ID:8},{ID:9}]");
this will cause JSON.NET to call only the empty constructor, so my itemIDs list remains empty. Also the Add method is not called.
How does JSON.NET add the items to the list so I can add logic at that place.
(this is about deserialization without properties that should be persistent in the json string, so the suggested duplicate question has nothing to do with this one)
Solution:
public class MyCustomList : IList<ItemWithID>
{
private HashSet<int> itemIDs = new HashSet<int>();
private List<ItemWithID> actualList = new List<ItemWithID>();
public void Add(ItemWithID item)
{
actualList.Add(item);
itemIDs.Add(item.ID);
}
public bool Remove(ItemWithID item)
{
var removed = actualList.Remove(item);
if (removed)
{
itemIDs.Remove(item.ID);
}
return removed;
}
public bool ContainsID(int id)
{
return itemIDs.Contains(id);
}
public int IndexOf(ItemWithID item)
{
return actualList.IndexOf(item);
}
public void Insert(int index, ItemWithID item)
{
actualList.Insert(index, item);
itemIDs.Add(item.ID);
}
public void RemoveAt(int index)
{
itemIDs.Remove(actualList[index].ID);
actualList.RemoveAt(index);
}
public ItemWithID this[int index]
{
get
{
return actualList[index];
}
set
{
actualList[index] = value;
if (!itemIDs.Contains(value.ID))
{
itemIDs.Add(value.ID);
}
}
}
public void Clear()
{
actualList.Clear();
itemIDs.Clear();
}
public bool Contains(ItemWithID item)
{
return actualList.Contains(item);
}
public void CopyTo(ItemWithID[] array, int arrayIndex)
{
actualList.CopyTo(array, arrayIndex);
}
public int Count
{
get { return actualList.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public IEnumerator<ItemWithID> GetEnumerator()
{
return actualList.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
You could deserialize to the form the constructor expects, then call that yourself.
var collection = JsonConvert.DeserializeObject<ItemID[]>("[{ID:8},{ID:9}]");
var aCustomList = new MyCustomList(collection);
Your problem isn't with JSON deserialization, your MyCustomList class needs to derive from IList if you want to be able to override the Add method. See THIS for details.
I'm trying to serialize a class with protobuf-net which contains an immutable collection as a member.
The collection type, ImmutableList<T>, implements ICollection<T> but returns true for the IsReadOnly property. So any attempts to modify it throw an exception.
Protobuf-net seems to rely on being able to call Add(T) after creating a collection in order to populate it. This obviously won't work with an immutable collection, which is a shame because protobuf-net works beautifully with all my other data types, which are also immutable.
So my question is, what options do I have to be able to serialize such collections?
The code for ImmutableList<T> is listed below:
public sealed class ImmutableList<T> : IList<T>, IList
{
private readonly T[] m_Items;
public ImmutableList(IEnumerable<T> source)
{
m_Items = source.ToArray();
}
public T[] ToArray()
{
T[] newArray = new T[m_Items.Length];
m_Items.CopyTo(newArray, 0);
return newArray;
}
private static void ThrowNotSupported()
{
throw new NotSupportedException("The attempted operation was not supported as the collection is read-only.");
}
#region IList<T> Members
int IList.Add(object value)
{
ThrowNotSupported();
return -1;
}
void IList.Clear()
{
ThrowNotSupported();
}
void IList<T>.Insert(int index, T item)
{
ThrowNotSupported();
}
void IList.Insert(int index, object value)
{
ThrowNotSupported();
}
void IList.Remove(object value)
{
ThrowNotSupported();
}
void IList.RemoveAt(int index)
{
ThrowNotSupported();
}
void IList<T>.RemoveAt(int index)
{
ThrowNotSupported();
}
T IList<T>.this[int index]
{
get
{
return m_Items[index];
}
set
{
ThrowNotSupported();
}
}
object IList.this[int index]
{
get
{
return m_Items[index];
}
set
{
ThrowNotSupported();
}
}
public T this[int index]
{
get
{
return m_Items[index];
}
}
bool IList.Contains(object value)
{
return Array.IndexOf(m_Items, value) != -1;
}
int IList.IndexOf(object value)
{
return Array.IndexOf(m_Items, value);
}
public int IndexOf(T item)
{
return Array.IndexOf(m_Items, item);
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
#endregion
#region ICollection<T> Members
void ICollection<T>.Add(T item)
{
ThrowNotSupported();
}
void ICollection<T>.Clear()
{
ThrowNotSupported();
}
bool ICollection<T>.Remove(T item)
{
ThrowNotSupported();
return false;
}
object ICollection.SyncRoot
{
get
{
return m_Items;
}
}
bool ICollection.IsSynchronized
{
get
{
return true;
}
}
public bool Contains(T item)
{
return IndexOf(item) != -1;
}
public void CopyTo(T[] array, int arrayIndex)
{
m_Items.CopyTo(array, arrayIndex);
}
void ICollection.CopyTo(Array array, int index)
{
m_Items.CopyTo(array, index);
}
public int Count
{
get
{
return m_Items.Length;
}
}
public bool IsReadOnly
{
get
{
return true;
}
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)m_Items).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_Items.GetEnumerator();
}
#endregion
}
At the moment there is no support for that; but it seems a reasonable scenario. It depends on what you mean (comments) by "out of the box"; if you mean "today, without code changed", it would need to use a surrogate against the DTO, or a shim property that exposed the immutable list as a mutable one; if you mean "moving forwards", I suspect we could look at list-constructors that take (perferable) IEnumerable[<T>] or (less preferable, but doable) T[], and simply construct the list after buffering the data.
This question already has answers here:
Immutable collections?
(10 answers)
Closed 9 years ago.
It seems to me there is an extreme lack of safe, immutable collection types for .NET, in particular BCL but I've not seen much work done outside either. Do anyone have any pointers to a (preferably) production quality, fast, immutable collections library for .NET. A fast list type is essential. I'm not yet prepared to switch to F#.
*Edit: Note to searchers, this is being rolled into the BCL soon: .NET immutable collections
You might want to take a look at the Microsoft.FSharp.Collections namespace in the FSharp.Core assembly. You do not have to program in F# to make use of these types.
Keep in mind that the names will be different when used from outside F#. For example, the Map in F# is known as FSharpMap from C#.
The .NET BCL team has released a Immutable Collections preview for .NET 4.5
Functional-dotnet by Alexey Romanov
Sasa by Sandro Magi
Kinet by Tony Morris
I wrote an ImmutableList<T> class some time ago :
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class ImmutableList<T> : IList<T>, IEquatable<ImmutableList<T>>
{
#region Private data
private readonly IList<T> _items;
private readonly int _hashCode;
#endregion
#region Constructor
public ImmutableList(IEnumerable<T> items)
{
_items = items.ToArray();
_hashCode = ComputeHash();
}
#endregion
#region Public members
public ImmutableList<T> Add(T item)
{
return this
.Append(item)
.AsImmutable();
}
public ImmutableList<T> Remove(T item)
{
return this
.SkipFirst(it => object.Equals(it, item))
.AsImmutable();
}
public ImmutableList<T> Insert(int index, T item)
{
return this
.InsertAt(index, item)
.AsImmutable();
}
public ImmutableList<T> RemoveAt(int index)
{
return this
.SkipAt(index)
.AsImmutable();
}
public ImmutableList<T> Replace(int index, T item)
{
return this
.ReplaceAt(index, item)
.AsImmutable();
}
#endregion
#region Interface implementations
public int IndexOf(T item)
{
if (_items == null)
return -1;
return _items.IndexOf(item);
}
public bool Contains(T item)
{
if (_items == null)
return false;
return _items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
if (_items == null)
return;
_items.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
if (_items == null)
return 0;
return _items.Count;
}
}
public IEnumerator<T> GetEnumerator()
{
if (_items == null)
return Enumerable.Empty<T>().GetEnumerator();
return _items.GetEnumerator();
}
public bool Equals(ImmutableList<T> other)
{
if (other == null || this._hashCode != other._hashCode)
return false;
return this.SequenceEqual(other);
}
#endregion
#region Explicit interface implementations
void IList<T>.Insert(int index, T item)
{
throw new InvalidOperationException();
}
void IList<T>.RemoveAt(int index)
{
throw new InvalidOperationException();
}
T IList<T>.this[int index]
{
get
{
if (_items == null)
throw new IndexOutOfRangeException();
return _items[index];
}
set
{
throw new InvalidOperationException();
}
}
void ICollection<T>.Add(T item)
{
throw new InvalidOperationException();
}
void ICollection<T>.Clear()
{
throw new InvalidOperationException();
}
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
bool ICollection<T>.Remove(T item)
{
throw new InvalidOperationException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Overrides
public override bool Equals(object obj)
{
if (obj is ImmutableList<T>)
{
var other = (ImmutableList<T>)obj;
return this.Equals(other);
}
return false;
}
public override int GetHashCode()
{
return _hashCode;
}
#endregion
#region Private methods
private int ComputeHash()
{
if (_items == null)
return 0;
return _items
.Aggregate(
983,
(hash, item) =>
item != null
? 457 * hash ^ item.GetHashCode()
: hash);
}
#endregion
}
All methods that modify the collection return a modified copy. In order to fulfill with the IList<T> interface contract, the standard Add/Remove/Delete/Clear methods are implemented explicitly, but they throw an InvalidOperationException.
This class uses a few non-standard extension methods, here they are :
public static class ExtensionMethods
{
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item)
{
return source.Concat(new[] { item });
}
public static IEnumerable<T> SkipFirst<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
bool skipped = false;
foreach (var item in source)
{
if (!skipped && predicate(item))
{
skipped = true;
continue;
}
yield return item;
}
}
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> source, int index)
{
return source.Where((it, i) => i != index);
}
public static IEnumerable<T> InsertAt<T>(this IEnumerable<T> source, int index, T item)
{
int i = 0;
foreach (var it in source)
{
if (i++ == index)
yield return item;
yield return it;
}
}
public static IEnumerable<T> ReplaceAt<T>(this IEnumerable<T> source, int index, T item)
{
return source.Select((it, i) => i == index ? item : it);
}
}
And here's a helper class to create instances of ImmutableList<T> :
public static class ImmutableList
{
public static ImmutableList<T> CreateFrom<T>(IEnumerable<T> source)
{
return new ImmutableList<T>(source);
}
public static ImmutableList<T> Create<T>(params T[] items)
{
return new ImmutableList<T>(items);
}
public static ImmutableList<T> AsImmutable<T>(this IEnumerable<T> source)
{
return new ImmutableList<T>(source);
}
}
Here's a usage example :
[Test]
public void Test_ImmutableList()
{
var expected = ImmutableList.Create("zoo", "bar", "foo");
var input = ImmutableList.Create("foo", "bar", "baz");
var inputSave = input.AsImmutable();
var actual = input
.Add("foo")
.RemoveAt(0)
.Replace(0, "zoo")
.Insert(1, "bar")
.Remove("baz");
Assert.AreEqual(inputSave, input, "Input collection was modified");
Assert.AreEqual(expected, actual);
}
I can't say it's production quality, as I haven't tested it thoroughly, but so far it seems to work just fine...
C5 springs to mind, but I'm not sure how fast it is. It has been around for years, and is very stable.
Additionally, List<T>.AsReadOnly() does the job rather well IMO, but unfortunately there is no equivalent for dictionaries or arbitrary ICollection<T>'s.
You may look at Extras or System.collections.concurrent tutorial
You could try BclExtras by JaredPar.
I am serializing Lists of classes which are my data entities. I have a DataProvider that contains a List.
I always modify items directly within the collection.
What is the best way of determining if any items in the List have changed? I am using the Compact Framework.
My only current idea is to create a hash of the List (if that's possible) when I load the list. Then when I do a save I re-get the hash of the list and see if they're different values. If they're different I save and then update the stored Hash for comparison later, if they're the same then I don't save.
Any ideas?
If the items you add to the list implement the INotifyPropertyChanged interface, you could build your own generic list that hooks the event in that interface for all objects you add to the list, and unhooks the event when the items are removed from the list.
There's a BindingList<T> class in the framework you can use, or you can write your own.
Here's a sample add method, assuming the type has been declared with where T: INotifyPropertyChanged:
public void Add(T item)
{
// null-check omitted for simplicity
item.PropertyChanged += ItemPropertyChanged;
_List.Add(item);
}
and the this[index] indexer property:
public T this[Int32 index]
{
get { return _List[index]; }
set {
T oldItem = _List[index];
_List[index] = value;
if (oldItem != value)
{
if (oldItem != null)
oldItem.PropertyChanged -= ItemPropertyChanged;
if (value != null)
value.PropertyChanged += ItemPropertyChanged;
}
}
}
If your items doesn't support INotifyPropertyChanged, but they're your classes, I would consider adding that support.
You could create your own IList<T> class, say DirtyList<T> that can record when the list has changed.
If you're willing to use reflection, the List<T> class has a private field called _version that is incremented every time the list changes. It won't tell you which items have changed, but you can compare it with the original value of _version to detect an unmodified list.
For reference, this field is used to ensure that enumerators become invalid when the list is modified. So you should be able to use it for your purposes fairly reliably, unless the actual managed code for List<T> changes.
To get the value of _version you can use something like this:
List<T> myList;
var field = myList.GetType().GetField("_version", BindingFlags.Instance | BindingFlags.NonPublic);
int version = field.GetValue(myList);
Generally speaking, though, this isn't the best approach. If you're stuck using a List<T> that someone else created, however, it's probably the best option you have. Please be aware that changes to the .NET framework could change the name of the field (or remove it entirely), and it's not guaranteed to exist in third-party CLR implementations like Mono.
How about something like this?
public class ItemChangedArgs<T> : EventArgs
{
public int Index { get; set; }
public T Item { get; set; }
}
public class EventList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable
{
private List<T> m_list;
public event EventHandler<ItemChangedArgs<T>> ItemAdded;
public event EventHandler<ItemChangedArgs<T>> ItemRemoved;
public event EventHandler<ItemChangedArgs<T>> ItemChanged;
public event EventHandler ListCleared;
public EventList(IEnumerable<T> collection)
{
m_list = new List<T>(collection);
}
public EventList(int capacity)
{
m_list = new List<T>(capacity);
}
public EventList()
{
m_list = new List<T>();
}
public void Add(T item)
{
Add(item, true);
}
public void Add(T item, Boolean raiseEvent)
{
m_list.Add(item);
if (raiseEvent) RaiseItemAdded(this.Count - 1, item);
}
public void AddRange(IEnumerable<T> collection)
{
foreach (T t in collection)
{
m_list.Add(t);
}
}
private void RaiseItemAdded(int index, T item)
{
if (ItemAdded == null) return;
ItemAdded(this, new ItemChangedArgs<T> { Index = index, Item = item });
}
public int IndexOf(T item)
{
return m_list.IndexOf(item);
}
public void Insert(int index, T item)
{
m_list.Insert(index, item);
RaiseItemAdded(index, item);
}
public void RemoveAt(int index)
{
T item = m_list[index];
m_list.RemoveAt(index);
RaiseItemRemoved(index, item);
}
private void RaiseItemRemoved(int index, T item)
{
if(ItemRemoved == null) return;
ItemRemoved(this, new ItemChangedArgs<T> { Index = index, Item = item });
}
public T this[int index]
{
get { return m_list[index]; }
set
{
m_list[index] = value;
RaiseItemChanged(index, m_list[index]);
}
}
private void RaiseItemChanged(int index, T item)
{
if(ItemChanged == null) return;
ItemChanged(this, new ItemChangedArgs<T> { Index = index, Item = item });
}
public void Clear()
{
m_list.Clear();
RaiseListCleared();
}
private void RaiseListCleared()
{
if(ListCleared == null) return;
ListCleared(this, null);
}
public bool Contains(T item)
{
return m_list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
m_list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return m_list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
for (int i = 0; i < m_list.Count; i++)
{
if(item.Equals(m_list[i]))
{
T value = m_list[i];
m_list.RemoveAt(i);
RaiseItemRemoved(i, value);
return true;
}
}
return false;
}
public IEnumerator<T> GetEnumerator()
{
return m_list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_list.GetEnumerator();
}
}
Assuming that GetHashCode() for every member contained in the list is implemented properly (and thus changes when an element changes) I'd imagine something along the lines of:
public class DirtyList<T> : List<T> {
private IList<int> hashCodes = new List<int> hashCodes();
public DirtyList() : base() { }
public DirtyList(IEnumerable<T> items) : base() {
foreach(T item in items){
this.Add(item); //Add it to the collection
hashCodes.Add(item.GetHashCode());
}
}
public override void Add(T item){
base.Add(item);
hashCodes.Add(item);
}
//Add more logic for the setter and also handle the case where items are removed and indexes change and etc, also what happens in case of null values?
public bool IsDirty {
get {
for(int i = 0; i < Count: i++){
if(hashCodes[i] != this[i].GetHashCode()){ return true; }
}
return false;
}
}
}
*Please be aware i typed this up on SO and do not have a compiler, so above stated code is in no way guarenteed to work, but hopefully it'll show the idea.
You could implement you're own list that maintains 2 internal lists... and instantiated version and tracking version... e.g.
//Rough Psuedo Code
public class TrackedList<T> : List<T>
{
public bool StartTracking {get; set; }
private List<T> InitialList { get; set; }
CTOR
{
//Instantiate Both Lists...
}
ADD(item)
{
if(!StartTracking)
{
Base.Add(item);
InitialList.Add(item);
}
else
{
Base.Add(item);
}
}
public bool IsDirty
{
get
{
Check if theres any differences between initial list and self.
}
}
}
Make sure that T is a descendant of an object that has a dirty flag and have the IList implementation have a check for that which walks the list's dirty flags.