Generic Pair .NET class

If you ever worked with C++ STL library you might remember pair template, which sometimes was very useful. .NET Framework has similar generic KeyValuePair<TKey, TValue>. But as it is designed to work with Dictionary class KeyValuePair has one sufficient constraint: it does not have public setters for Key and Value properties.

So I wrote my own generic Pair class and extended it with some useful static routines.

namespace OXT.Utils
{
	[Serializable]
	public class Pair<TFirst, TSecond>;
	{
		public Pair()
		{
		}
 
		public Pair(TFirst first, TSecond second)
		{
			this.first = first;
			this.second = second;
		}
 
		private TFirst first;
		public TFirst First
		{
			get { return first; }
			set { first = value; }
		}
 
		private TSecond second;
		public TSecond Second
		{
			get { return second; }
			set { second = value; }
		}
 
		public override bool Equals(object obj)
		{
			if (this == obj) return true;
			Pair<TFirst, TSecond> pair = obj as Pair<TFirst, TSecond>;
			if (pair == null) return false;
			return Equals(first, pair.first) && Equals(second, pair.second);
		}
 
		public override int GetHashCode()
		{
			return (first != null ? first.GetHashCode() : 0) + 29*(second != null ? second.GetHashCode() : 0);
		}
 
		public static List<Pair<TFirst, TSecond>> Dictionary2List(IDictionary<TFirst, TSecond> dictionary)
		{
			List<Pair<TFirst, TSecond>> result = new List<Pair<TFirst, TSecond>>();
			if (dictionary != null)
			{
				foreach (KeyValuePair<TFirst, TSecond> pair in dictionary)
				{
					result.Add(new Pair<TFirst, TSecond>(pair.Key, pair.Value));
				}
			}
			return result;
		}
 
		public static Dictionary<TFirst, TSecond> List2Dictionary(IList<Pair<TFirst, TSecond>> list)
		{
			Dictionary<TFirst, TSecond> result = new Dictionary<TFirst, TSecond>();
			if (list != null)
			{
				foreach (Pair<TFirst, TSecond> pair in list)
				{
					result.Add(pair.First, pair.Second);
				}
			}
			return result;
		}
 
		public static Dictionary<TFirst, List<TSecond>> List2TwoDimentionalDictionary(IList<Pair<TFirst, TSecond>> list)
		{
			Dictionary<TFirst, List<TSecond>> result = new Dictionary<TFirst, List<TSecond>>();
			if (list != null)
			{
				foreach (Pair<TFirst, TSecond> pair in list)
				{
					List<TSecond> dimentionList;
					if (!result.TryGetValue(pair.First, out dimentionList))
					{
						dimentionList = new List<TSecond>();
						result[pair.First] = dimentionList;
					}
 
					dimentionList.Add(pair.Second);
				}
			}
			return result;
		}
 
	}

Tags: , ,

AddThis Social Bookmark Button

One Response to “Generic Pair .NET class”

  1. Michael Freidgeim Says:

    Thank for the class.
    Note that your page is quite narrow and right part of the code is not visible. Scrollbox on the bootom is not obvious,if you are at the top of the page.

Leave a Reply