I know there are a lots of questions (1, 2, 3, 4, 5, etc) about that error, but I can't find one that explains the cause of this error and suitable for my case. Let me know if I miss one!
First of all, I am binding to my DataGrid ItemsSource with a custom class (not ObservableCollection or any other .NET built-in observable collection). Before showing you its code, let me explain how I thought of it (my assumptions are may be be wrong).
In my mind, to be bindable, a collection must implements at least IEnumerable and INotifyCollectionChanged. IEnumerable in order to the view to get the items to display (thanks to the GetEnumerator method) and INotifyCollectionChanged in order to the view to know the changes on the collection.
So I end up with this class:
public class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IEnumerable<TValue>, INotifyCollectionChanged
{
#region fields
private IDictionary<TKey, TValue> _innerDictionary;
#endregion
#region properties
public int Count { get { return _innerDictionary.Count; } }
public ICollection<TKey> Keys { get { return _innerDictionary.Keys; } }
public ICollection<TValue> Values { get { return _innerDictionary.Values; } }
public bool IsReadOnly { get { return false; } }
#endregion
#region indexors
public TValue this[TKey key]
{
get { return _innerDictionary[key]; }
set { this.InternalAdd(new KeyValuePair<TKey, TValue>(key, value)); }
}
#endregion
#region events
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
#region constructors
public ObservableDictionary()
{
_innerDictionary = new Dictionary<TKey, TValue>();
}
public ObservableDictionary(int capacity)
{
_innerDictionary = new Dictionary<TKey, TValue>(capacity);
}
public ObservableDictionary(IEqualityComparer<TKey> comparer)
{
_innerDictionary = new Dictionary<TKey, TValue>(comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary)
{
_innerDictionary = new Dictionary<TKey, TValue>(dictionary);
}
public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_innerDictionary = new Dictionary<TKey, TValue>(capacity, comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_innerDictionary = new Dictionary<TKey, TValue>(dictionary, comparer);
}
#endregion
#region public methods
public bool ContainsKey(TKey key)
{
return _innerDictionary.ContainsKey(key);
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _innerDictionary.Contains(item);
}
public void Add(TKey key, TValue value)
{
this.InternalAdd(new KeyValuePair<TKey, TValue>(key, value));
}
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
if (!items.Any())
{
return;
}
var added = new List<TValue>();
var removed = new List<TValue>();
foreach (var item in items)
{
TValue value;
if (_innerDictionary.TryGetValue(item.Key, out value))
{
removed.Add(value);
}
added.Add(item.Value);
_innerDictionary[item.Key] = item.Value;
}
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, null));
if (removed.Count > 0)
{
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, removed));
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
this.InternalAdd(item);
}
public bool TryGetValue(TKey key, out TValue value)
{
return _innerDictionary.TryGetValue(key, out value);
}
public bool Remove(TKey key)
{
return this.InternalRemove(key);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return this.InternalRemove(item.Key);
}
public void Clear()
{
_innerDictionary.Clear();
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_innerDictionary.CopyTo(array, arrayIndex);
}
public IEnumerator<TValue> GetEnumerator()
{
return Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return _innerDictionary.GetEnumerator();
}
#endregion
#region private methods
/// <summary>
/// Adds the specified value to the internal dictionary and indicates whether the element has actually been added. Fires the CollectionChanged event accordingly.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
private void InternalAdd(KeyValuePair<TKey, TValue> item)
{
IList added = new TValue[] { item.Value };
TValue value;
if (_innerDictionary.TryGetValue(item.Key, out value))
{
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, new TValue[] { value }));
}
_innerDictionary[item.Key] = item.Value;
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, null));
}
/// <summary>
/// Remove the specified key from the internal dictionary and indicates whether the element has actually been removed. Fires the CollectionChanged event accordingly.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
private bool InternalRemove(TKey key)
{
TValue value;
if (_innerDictionary.TryGetValue(key, out value))
{
_innerDictionary.Remove(key);
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, new TValue[] { value }));
}
return value != null;
}
#endregion
}
It implements implicitly the IEnumerable<TValue>.GetEnumerator and explicitly the others GetEnumerator methods (IDictionary and IEnumerable) in order to my view display only the values of my dictionary, and I map the add/remove methods around the invocation of the CollectionChanged event.
My ViewModel is defined like this:
class MyViewModel
{
public ObservableDictionary<string, Foo> Foos { get; private set; }
public MyViewModel()
{
this.Foos = new ObservableDictionary<string, Foo>();
}
}
And bind it to my view like this:
<DataGrid ItemsSource="{Binding Facts}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True" Width="*" />
<DataGridTextColumn Header="Type" Binding="{Binding Type}" IsReadOnly="True" Width="*" />
<DataGridTextColumn Header="Value" Binding="{Binding Value}" IsReadOnly="False" Width="*" />
</DataGrid.Columns>
</DataGrid>
Then, when I try to edit the Value, I get the specified error:
'EditItem' is not allowed for this view
When I put some breakpoints in my code, I never reach the ObservableDictionary indexor setter nor Foo.Value setter.
Are my thoughts about how the view gets the item from the binded collection corrects? Why am I getting this error and/or how can I authorize my view to EditItem?
Your source collection type (ObservableDictionary<TKey, TValue>) should implement the IList interface if you want to be able to edit the data in a DataGrid.
Whenever you bind to some collection property in WPF, you are always binding to an automatically generated view and not to the actual source collection itself.
The type of view that is created for you by the runtime depends on the type of the source collection and your source collection must implement the non-generic IList interface for the internal editing functionality of the DataGrid control to work.
Related
I am writing a custom observable collection for some of my needs and I want it to allow EditItem when used within a WPF DataGrid.
(see the code of the collection at the end of the question to avoid polluting the reading of the question)
You will see that I thought of 3 solutions. But I cannot get any of them working for now.
Solution 1
According to this question, if I want my ObservableDictionary to allow EditItem, it has to implement the non-generic IList. But as I am using a IDictionary as backing field to store the elements, it is impossible to properly implement the IList interface (because it is based on ordered index).
Unless someone find a way?
Solution 2
Next idea, instead of letting the system chose the CollectionView implementation, I can force it to use my own, like this:
<CollectionViewSource
x:Key="FooesSource"
Source="{Binding Fooes}"
CollectionViewType="local:MyCollectionView" />
To do so, I tried to override one existing CollectionView, one allowing EditItem, to suit my needs. For example:
class ObservableDictionaryCollectionView : ListCollectionView
{
public ObservableDictionaryCollectionView(IDictionary dictionary)
: base(dictionary.Values)
{
}
}
But it does not work because dictionary.Values is a ICollection and ICollection does not implement IList (it is the opposite -_-).
Is there another built-in CollectionView that could suit my needs?
Solution 3
Based on the next idea, I could try to write my own, from scratch, CollectionView. But before doing this, I would like to know:
If anyone has a better idea?
If it is possible?
May be some dictionary constraints made this impossible? Which interfaces should I implement? (IEditableCollectionView, IEditableCollectionViewAddNewItem, IEditableCollectionView, ICollectionViewLiveShaping, etc)
As promised, here is the code of the collection:
public class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IEnumerable<TValue>, INotifyCollectionChanged
{
#region fields
private IDictionary<TKey, TValue> _innerDictionary;
#endregion
#region properties
public int Count { get { return _innerDictionary.Count; } }
public ICollection<TKey> Keys { get { return _innerDictionary.Keys; } }
public ICollection<TValue> Values { get { return _innerDictionary.Values; } }
public bool IsReadOnly { get { return false; } }
#endregion
#region indexors
public TValue this[TKey key]
{
get { return _innerDictionary[key]; }
set { this.InternalAdd(new KeyValuePair<TKey, TValue>(key, value)); }
}
#endregion
#region events
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
#region constructors
public ObservableDictionary()
{
_innerDictionary = new Dictionary<TKey, TValue>();
}
public ObservableDictionary(int capacity)
{
_innerDictionary = new Dictionary<TKey, TValue>(capacity);
}
public ObservableDictionary(IEqualityComparer<TKey> comparer)
{
_innerDictionary = new Dictionary<TKey, TValue>(comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary)
{
_innerDictionary = new Dictionary<TKey, TValue>(dictionary);
}
public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_innerDictionary = new Dictionary<TKey, TValue>(capacity, comparer);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_innerDictionary = new Dictionary<TKey, TValue>(dictionary, comparer);
}
#endregion
#region public methods
public bool ContainsKey(TKey key)
{
return _innerDictionary.ContainsKey(key);
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _innerDictionary.Contains(item);
}
public void Add(TKey key, TValue value)
{
this.InternalAdd(new KeyValuePair<TKey, TValue>(key, value));
}
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
if (!items.Any())
{
return;
}
var added = new List<TValue>();
var removed = new List<TValue>();
foreach (var item in items)
{
TValue value;
if (_innerDictionary.TryGetValue(item.Key, out value))
{
removed.Add(value);
}
added.Add(item.Value);
_innerDictionary[item.Key] = item.Value;
}
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, null));
if (removed.Count > 0)
{
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, removed));
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
this.InternalAdd(item);
}
public bool TryGetValue(TKey key, out TValue value)
{
return _innerDictionary.TryGetValue(key, out value);
}
public bool Remove(TKey key)
{
return this.InternalRemove(key);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return this.InternalRemove(item.Key);
}
public void Clear()
{
_innerDictionary.Clear();
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_innerDictionary.CopyTo(array, arrayIndex);
}
public IEnumerator<TValue> GetEnumerator()
{
return Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return _innerDictionary.GetEnumerator();
}
#endregion
#region private methods
/// <summary>
/// Adds the specified value to the internal dictionary and indicates whether the element has actually been added. Fires the CollectionChanged event accordingly.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
private void InternalAdd(KeyValuePair<TKey, TValue> item)
{
IList added = new TValue[] { item.Value };
TValue value;
if (_innerDictionary.TryGetValue(item.Key, out value))
{
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, new TValue[] { value }));
}
_innerDictionary[item.Key] = item.Value;
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, null));
}
/// <summary>
/// Remove the specified key from the internal dictionary and indicates whether the element has actually been removed. Fires the CollectionChanged event accordingly.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
private bool InternalRemove(TKey key)
{
TValue value;
if (_innerDictionary.TryGetValue(key, out value))
{
_innerDictionary.Remove(key);
this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, null, new TValue[] { value }));
}
return value != null;
}
#endregion
}
You could build an ObservableCollection that implements both Dictionary and List, by doubly storing the inserted data into an internal list and a dictionary. The Dictionary provides the advantages of a dictionary, the List providing the better support for Binding Operations.
Disadvantages include doubling up your memory usage, and hurting your item removal time*
* Inserts** and Accesses have the same efficiency as a regular dictionary, but removal has to find the item in the internal list as well
** I guess inserts can also be more costly on the occasions they require array resizes.
I am trying to create a custom ReadOnlyDictionary<TKey, TValue> for .NET 4.0. The approach is to keep a private Dictionary<TKey, TValue> object as well as flags to determine whether adding/removing and item assignment is allowed.
This works fine but I wanted to implement the IDictionary<TKey, TValue> interface for completeness. However, I notice that it extends ICollection<KeyValuePair<TKey, TValue>> whereas none of its properties or methods appear in the Dictionary<TKey, TValue> class. How is this possible? If the interface is implemented, why are ICollection members not exposed?
Furthermore, why does the Dictionary class need to implement ICollection in the first place?
Here is a rough implementation:
public sealed class ReadOnlyDictionary<TKey, TValue>:
//IDictionary<TKey, TValue>,
IEnumerable<KeyValuePair<TKey, TValue>>
{
#region Members.
public bool AllowListEdit { get; private set; }
public bool AllowItemEdit { get; private set; }
private Dictionary<TKey, TValue> Dictionary { get; set; }
#endregion Members.
#region Constructors.
public ReadOnlyDictionary (bool allowListEdit, bool allowItemEdit) { this.AllowListEdit = allowListEdit; this.AllowItemEdit = allowItemEdit; this.Dictionary = new Dictionary<TKey, TValue>(); }
public ReadOnlyDictionary (IEqualityComparer<TKey> comparer, bool allowListEdit, bool allowItemEdit) { this.AllowListEdit = allowListEdit; this.AllowItemEdit = allowItemEdit; this.Dictionary = new Dictionary<TKey, TValue>(comparer); }
public ReadOnlyDictionary (IDictionary<TKey, TValue> dictionary, bool allowListEdit = false, bool allowItemEdit = false) : this(allowListEdit, allowItemEdit) { foreach (var pair in dictionary) { this.Dictionary.Add(pair.Key, pair.Value); } }
public ReadOnlyDictionary (IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer, bool allowListEdit = false, bool allowItemEdit = false) : this(comparer, allowListEdit, allowItemEdit) { foreach (var pair in dictionary) { this.Dictionary.Add(pair.Key, pair.Value); } }
#endregion Constructors.
#region Properties.
public int Count { get { return (this.Dictionary.Count); } }
public IEqualityComparer<TKey> Comparer { get { return (this.Dictionary.Comparer); } }
#endregion Properties.
#region Methods.
private void ThrowItemReadOnlyException () { if (this.AllowListEdit) { throw (new NotSupportedException("This collection does not allow editing items.")); } }
private void ThrowListReadOnlyException () { if (this.AllowItemEdit) { throw (new NotSupportedException("This collection does not allow adding and removing items.")); } }
public bool ContainsValue (TValue value) { return (this.Dictionary.ContainsValue(value)); }
public void Clear () { this.ThrowListReadOnlyException(); this.Dictionary.Clear(); }
#endregion Methods.
#region Interface Implementation: IEnumerable<KeyValuePair<TKey, TValue>>.
IEnumerator IEnumerable.GetEnumerator () { return (this.Dictionary.GetEnumerator()); }
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator () { return (this.Dictionary.GetEnumerator()); }
#endregion Interface Implementation: IEnumerable<KeyValuePair<TKey, TValue>>.
#region Interface Implementation: ICollection<KeyValuePair<TKey, TValue>>.
//public int Count { get { return (this.Dictionary.Count); } }
//public bool IsReadOnly { get { return (this.AllowListEdit); } }
//public bool Contains (KeyValuePair<TKey, TValue> item) { throw (new NotImplementedException()); }
//public void Clear () { throw (new NotImplementedException()); }
//public void Add (KeyValuePair<TKey, TValue> item) { throw (new NotImplementedException()); }
//public void CopyTo (KeyValuePair<TKey, TValue> [] array, int arrayIndex) { throw (new NotImplementedException()); }
//public bool Remove (KeyValuePair<TKey, TValue> item) { throw (new NotImplementedException()); }
#endregion Interface Implementation: ICollection<KeyValuePair<TKey, TValue>>.
#region Interface Implementation: IDictionary<TKey, TValue>.
//====================================================================================================
// Interface Implementation: IDictionary<TKey, TValue>.
//====================================================================================================
public Dictionary<TKey, TValue>.KeyCollection Keys { get { return (this.Dictionary.Keys); } }
public Dictionary<TKey, TValue>.ValueCollection Values { get { return (this.Dictionary.Values); } }
public TValue this [TKey key] { get { return (this.Dictionary [key]); } set { this.ThrowItemReadOnlyException(); this.Dictionary [key] = value; } }
public void Add (TKey key, TValue value) { this.ThrowListReadOnlyException(); this.Dictionary.Add(key, value); }
public bool ContainsKey (TKey key) { return (this.Dictionary.ContainsKey(key)); }
public bool Remove (TKey key) { this.ThrowListReadOnlyException(); return (this.Dictionary.Remove(key)); }
public bool TryGetValue (TKey key, out TValue value) { return (this.Dictionary.TryGetValue(key, out value)); }
#endregion Interface Implementation: IDictionary<TKey, TValue>.
}
Dictionary<TKey, TValue> implements the ICollection<KeyValuePair<TKey, TValue>> interface explicitly.
As you can see on the MSDN page for Dictionary, these methods are listed under "Explicit interface implementations".
Explicitly implementing an interface means that those methods will not be available through the concrete type. You'll have to cast the dictionary to an ICollection<T> to be able to call them.
Dictionary<int, int> dict = new Dictionary<int, int>();
bool sync = dict.IsSynchronized; // not allowed
ICollection<KeyValuePair<int, int>> dict = new Dictionary<int, int>();
bool sync = dict.IsSynchronized; // allowed
More on explicit interface implementations: http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx
How can I change the way a dictionary works, so that if there is no KVP with given key, it returns a default value, without wrapping usual dic["nonexistentKey"] with try-catch?
You could make your own class which encapsulates a Dictionary<TKey,TValue>, and implements IDictionary<TKey,TValue>.
This will behave like a dictionary, but you can write the behavior to handle your non-existent key any way you wish.
However, you can't change the way the actual Dictionary<TKey,TValue> class functions.
You can also add an extension method to IDictionary, or Dictionary if you prefer.
public static class IDictionaryExtensions
{
public static TValue ValueAtOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
if (dictionary == null || !dictionary.ContainsKey(key))
{
return defaultValue;
}
return dictionary[key];
}
}
Note that you may want to throw an ArgumentNullException if the dictionary is null, rather than returning the default value as in the example... whatever is appropriate for you.
Use Dictionary.TryGetValue :
Dictionary<int, YourType> dictionary = ...;
YourType x;
if (!dictionary.TryGetValue(123, out x))
{
x = new YourType();
}
// here X will be assigned to the value or the default if the key was not present.
If you really need to override the default dictionary[key] approach, you can use this class (as either the dictionary itself or as a wrapper for an existing dictionary):
/// <summary>
/// A dictionary implementation that returns the default value of <typeparamref name="TValue"/> when the key is not present in the dictionary.
/// </summary>
public class DictionaryWithDefaults<TKey, TValue> : IDictionary<TKey, TValue>
{
/// <summary>
/// Holds the actual data using standard dictionary.
/// </summary>
private IDictionary<TKey, TValue> _storage;
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryWithDefaults{TValue}" /> class.
/// The data is stored directly in this dictionary.
/// </summary>
public DictionaryWithDefaults()
{
this._storage = new Dictionary<TKey, TValue>();
}
/// <summary>
/// Initializes a new instance of the <see cref="DictionaryWithDefaults{TValue}" /> class.
/// This dictionary acts as a wrapper for the data stored in the dictionary <paramref name="forWrapping" />.
/// </summary>
/// <param name="forWrapping">The dictionary object for wrapping.</param>
/// <exception cref="System.ArgumentNullException">when <paramref name="forWrapping"/> is <c>null</c></exception>
public DictionaryWithDefaults(IDictionary<TKey, TValue> forWrapping)
{
if (forWrapping == null)
throw new ArgumentNullException("forWrapping");
this._storage = forWrapping;
}
public void Add(TKey key, TValue value)
{
this._storage.Add(key, value);
}
public bool ContainsKey(TKey key)
{
return this._storage.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return this._storage.Keys; }
}
public bool Remove(TKey key)
{
return this._storage.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
// always return a value, even if the key does not exist.
// this is also the only place one would modify if the default value has to be customized (passed in the constructor etc.)
if (!this._storage.TryGetValue(key, out value))
value = default(TValue);
return true;
}
public ICollection<TValue> Values
{
get { return this._storage.Values; }
}
public TValue this[TKey key]
{
get
{
TValue value;
this.TryGetValue(key, out value);
return value;
}
set
{
this._storage[key] = value;
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
this._storage.Add(item);
}
public void Clear()
{
this._storage.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return this._storage.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this._storage.CopyTo(array, arrayIndex);
}
public int Count
{
get { return this._storage.Count; }
}
public bool IsReadOnly
{
get { return this._storage.IsReadOnly; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return this._storage.Remove(item);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return this._storage.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this._storage.GetEnumerator();
}
}
No, you have to wrap it. this[] is not a virtual method and cannot be overridden.
So your best bet is to create a simple class that exposes IDictionary (or only selected methods) and that wraps the this[] get with a try/catch.
I'm completely new to C#, so I'm about to make a horrible attempt at my own version of an OrderedDictionary unless someone can suggest an alternative.
I need to be able to access my elements by array index, retaining the order they were added, and I also will be frequently updating individual elements using their key.
Is there a collection that allows this on the phone?
If I keep a List and Dictionary will they both be pointing to the same item or is there some kind of pointer thing I have to do?:
Item i = new Item();
list.Add(i);
dict.Add("key", i);
Here's my implementation (comes from the open source OpenNETCF Extensions library):
public class OrderedDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
private Dictionary<TKey, TValue> m_dictionary;
private List<TValue> m_list = new List<TValue>();
private object m_syncRoot = new object();
public OrderedDictionary()
{
m_dictionary = new Dictionary<TKey, TValue>();
}
public OrderedDictionary(IEqualityComparer<TKey> comparer)
{
m_dictionary = new Dictionary<TKey, TValue>(comparer);
}
public void Add(TKey key, TValue value)
{
lock (m_syncRoot)
{
m_dictionary.Add(key, value);
m_list.Add(value);
}
}
public TValue this[int index]
{
get { return m_list[index]; }
}
public TValue this[TKey key]
{
get { return m_dictionary[key]; }
}
public int Count
{
get { return m_dictionary.Count; }
}
public Dictionary<TKey, TValue>.KeyCollection Keys
{
get { return m_dictionary.Keys; }
}
public Dictionary<TKey, TValue>.ValueCollection Values
{
get { return m_dictionary.Values; }
}
public void Clear()
{
lock (m_syncRoot)
{
m_dictionary.Clear();
m_list.Clear();
}
}
public bool ContainsKey(TKey key)
{
return m_dictionary.ContainsKey(key);
}
public bool ContainsValue(TValue value)
{
return m_dictionary.ContainsValue(value);
}
public void Insert(int index, TKey key, TValue value)
{
lock (m_syncRoot)
{
m_list.Insert(index, value);
m_dictionary.Add(key, value);
}
}
public void Remove(TKey key)
{
lock (m_syncRoot)
{
if (ContainsKey(key))
{
var existing = m_dictionary[key];
m_list.Remove(existing);
m_dictionary.Remove(key);
}
}
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return m_dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Using a List and a Dictionary is probably a good option actually. The "pointer thing" that you're talking about happens by default for Objects in .NET (any class and/or structure). All objects in .NET are passed around by reference.
So, if you use:
Item i = new Item();
list.Add(i);
dict.Add("key",i);
Console.WriteLine(list.Last() == dict["key"]);
Your output will be "true".
Best of luck!
I won't suggest using OrderedDictionary, since it's a non-generic container.
However, if you just want to use it like always. You can port Mono's version of OrderedDictionary.
https://github.com/mono/mono/blob/master/mcs/class/System/System.Collections.Specialized/OrderedDictionary.cs
Here's some tips if you want to port this:
Remove any unavailable interface
Remove serialization-related code
Replace ArrayList with List<object>
Replace Hashtable with Dictionary<object, object>
I thought of solution below because the collection is very very small. But what if it was big?
private Dictionary<string, OfTable> _folderData = new Dictionary<string, OfTable>();
public Dictionary<string, OfTable> FolderData
{
get { return new Dictionary<string,OfTable>(_folderData); }
}
With List you can make:
public class MyClass
{
private List<int> _items = new List<int>();
public IList<int> Items
{
get { return _items.AsReadOnly(); }
}
}
That would be nice!
Thanks in advance, Cheers & BR - Matti
NOW WHEN I THINK THE OBJECTS IN COLLECTION ARE IN HEAP. SO MY SOLUTION DOES NOT PREVENT THE CALLER TO MODIFY THEM!!! CAUSE BOTH Dictionary s CONTAIN REFERENCES TO SAME OBJECT. DOES THIS APPLY TO List EXAMPLE ABOVE?
class OfTable
{
private int _table;
private List<int> _classes;
private string _label;
public OfTable()
{
_classes = new List<int>();
}
public int Table
{
get { return _table; }
set { _table = value; }
}
public List<int> Classes
{
get { return _classes; }
set { _classes = value; }
}
public string Label
{
get { return _label; }
set { _label = value; }
}
}
so how to make this immutable??
It's not difficult to roll your own ReadOnlyDictionary<K,V> wrapper class. Something like this:
public sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _dictionary;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
public int Count
{
get { return _dictionary.Count; }
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
public ICollection<TKey> Keys
{
get { return _dictionary.Keys; }
}
public bool TryGetValue(TKey key, out TValue value)
{
return _dictionary.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get { return _dictionary.Values; }
}
public TValue this[TKey key] // Item
{
get { return _dictionary[key]; }
}
#region IDictionary<TKey, TValue> Explicit Interface Implementation
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException("Dictionary is read-only.");
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException("Dictionary is read-only.");
}
TValue IDictionary<TKey, TValue>.this[TKey key] // Item
{
get { return _dictionary[key]; }
set { throw new NotSupportedException("Dictionary is read-only."); }
}
#endregion
#region ICollection<T> Explicit Interface Implementation
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException("Collection is read-only.");
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException("Collection is read-only.");
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return _dictionary.Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_dictionary.CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException("Collection is read-only.");
}
#endregion
#region IEnumerable Explicit Interface Implementation
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_dictionary).GetEnumerator();
}
#endregion
}
If you're using C#3 or later then you could knock-up a matching AsReadOnly extension method too:
public static class ReadOnlyDictionaryHelper
{
public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
var temp = dictionary as ReadOnlyDictionary<TKey, TValue>;
return temp ?? new ReadOnlyDictionary<TKey, TValue>(dictionary);
}
}
And then return the read-only wrapper from your property:
// in C#2
return new ReadOnlyDictionary<string, OfTable>(_folderData);
// in C#3 or later
return _folderData.AsReadOnly();
Use ReadOnlyCollection<T> class.
An instance of the ReadOnlyCollection generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes. See Collection for a modifiable version of this class.
--EDIT--
Checkout a trivial dictionary wrapper here. And A Generic Read-Only Dictionary by Richard Carr.