Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Maintaining collection
Message
From
24/05/2013 06:41:33
 
 
To
23/05/2013 14:52:04
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
VB 9.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Application:
Web
Miscellaneous
Thread ID:
01574508
Message ID:
01574632
Views:
38
>>>Well - I made the key part of the data for simplicity - it doesn't need to be
>>>
>>>If you go for a KeyedCollection, wouldn't you need to subclass KeyedCollection first (and implement GetKeyForItem() ? http://msdn.microsoft.com/en-us/library/ms132454.aspx)
>>
>>Yes. Maybe not worth the candle but would be simpler when adding items etc......
>
>The class at http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx looks like a good generic version to use.

Could expand on that to handle Michel's original problem:
 public class Program
    {
        private static void Main(string[] args)
        {
            var keyd2 = new KeyedCollectionEx<string, MyData>(myData => myData.Name);
            
            var md = new MyData { Name = "Tom", Data = "Test" };
            keyd2.Upsert(md);   

            md.Data = "Changed";
            keyd2.Upsert(md);

            var md2 = new MyData {Name = "Dick", Data = "New"};
            keyd2.Upsert(md2);
        }
    }

    public class MyData
    {
        public string Name{ get; set; }
        public string Data { get; set; }
    }

    public class KeyedCollectionEx<TKey, TItem> : KeyedCollection<TKey, TItem>
    {
        private readonly Func<TItem, TKey> _getKeyForItemDelegate;
        public KeyedCollectionEx(Func<TItem, TKey> getKeyForItemDelegate)
            : base()
        {
            if (getKeyForItemDelegate == null)
                throw new ArgumentNullException();

            _getKeyForItemDelegate = getKeyForItemDelegate;
        }

        protected override TKey GetKeyForItem(TItem item)
        {
            return _getKeyForItemDelegate(item);
        }

        public  void Upsert(TItem input)
        {
            int i = IndexOf(input);
            if (i == -1){Add(input);}
            else{SetItem(i,input);}
        }
    }
Previous
Reply
Map
View

Click here to load this message in the networking platform