Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- using System.ComponentModel;
- namespace Core
- {
- /// <summary>
- /// Used to hold various key-value data
- /// </summary>
- [Serializable]
- [DebuggerDisplay("Key = {Key}, Value = {Value}")]
- public class KeyItem
- {
- string _key;
- string _value;
- public string Key
- {
- get { return _key; }
- set { _key = value; }
- }
- public string Value
- {
- get { return _value; }
- set { _value = value; }
- }
- public KeyItem() { }
- public KeyItem(string k, string v)
- {
- _key = k;
- _value = v;
- }
- }
- /// <summary>
- /// Collection of <seealso cref="KeyItem"/> objects that holds basic key-value data
- /// </summary>
- [Serializable]
- [DebuggerDisplay("Count = {Count}")]
- public class KeyItemCollection : List<KeyItem>
- {
- public bool TryGetValue(string key, out KeyItem item)
- {
- item = this.FirstOrDefault(t => t.Key == key);
- return item != null;
- }
- #region Indexer
- public string this[string key]
- {
- get
- {
- KeyItem kitem = null;
- if (this.TryGetValue(key, out kitem))
- return kitem.Value;
- return null;
- }
- set
- {
- KeyItem kitem = null;
- if (this.TryGetValue(key, out kitem))
- {
- kitem.Value = value;
- }
- else
- {
- this.Add(new KeyItem(key, value));
- }
- }
- }
- #endregion
- #region ValueAs methods
- public string ValueAsString(string key, string valueIfNull = default(string))
- {
- KeyItem kitem = null;
- if (!this.TryGetValue(key, out kitem))
- return valueIfNull;
- if (string.IsNullOrEmpty(kitem.Value))
- {
- return valueIfNull;
- }
- else
- return kitem.Value;
- }
- public int ValueAsInt(string key, int valueIfNull = default(int))
- {
- return ValueAs<int>(key, valueIfNull);
- }
- public T ValueAs<T>(string key, T valueIfNull = default(T))
- {
- KeyItem kitem = null;
- Type valType = typeof(T);
- if (!this.TryGetValue(key, out kitem))
- return valueIfNull;
- if (kitem == null)
- {
- return valueIfNull;
- }
- if (valType.IsGenericType && valType.GetGenericTypeDefinition() == typeof(Nullable<>))
- {
- if (string.IsNullOrEmpty(kitem.Value))
- {
- return valueIfNull;
- }
- else
- {
- TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
- return (T)conv.ConvertFrom(kitem.Value);
- }
- }
- else
- {
- if (string.IsNullOrEmpty(kitem.Value))
- {
- return valueIfNull;
- }
- }
- return (T)Convert.ChangeType(kitem.Value, typeof(T));
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment