|
using System;
using System.Collections.Generic;
using System.Text;
namespace QiHe.CodeLib
{
[Serializable]
public class Set<T> : List<T>
{
public Set() { }
public Set(params T[] items)
: this()
{
this.AddRange(items);
}
public Set<T> Clone()
{
Set<T> clone = new Set<T>();
clone.AddRange(this);
return clone;
}
public static readonly Set<T> Empty = new Set<T>();
/// <summary>
/// Add a item if it is not contained in the set.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public new int Add(T item)
{
if (this.Contains(item))
{
return this.IndexOf(item);
}
else
{
base.Add(item);
return this.Count - 1;
}
}
/// <summary>
/// Add a set of items.
/// </summary>
/// <param name="items"></param>
public new void AddRange(IEnumerable<T> items)
{
foreach (T item in items)
{
this.Add(item);
}
}
public Set<T> SubSet(IList<int> indice)
{
Set<T> subset = new Set<T>();
foreach (int index in indice)
{
subset.Add(this[index]);
}
return subset;
}
public override string ToString()
{
return CodeLib.StringHelper.ContactWithDelim<T>(this, ",", "{", "}");
}
/// <summary>
/// Union
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns></returns>
public static Set<T> operator +(Set<T> A, Set<T> B)
{
Set<T> sum = new Set<T>();
sum.AddRange(A);
sum.AddRange(B);
return sum;
}
/// <summary>
/// Difference
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns></returns>
public static Set<T> operator -(Set<T> A, Set<T> B)
{
Set<T> diff = new Set<T>();
foreach (T item in A)
{
if (!B.Contains(item))
{
diff.Add(item);
}
}
return diff;
}
/// <summary>
/// Intersect
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns></returns>
public static Set<T> operator *(Set<T> A, Set<T> B)
{
Set<T> common = new Set<T>();
foreach (T item in A)
{
if (B.Contains(item))
{
common.Add(item);
}
}
return common;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.