Skip to content

Instantly share code, notes, and snippets.

@oillio
Created September 4, 2010 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oillio/564818 to your computer and use it in GitHub Desktop.
Save oillio/564818 to your computer and use it in GitHub Desktop.
//MultiDictionary is a Dictionary-like object that can store multiple values for the same key.
public class MultiDictionary<TKey, TValue> :ICollection<KeyValuePair<TKey, TValue>>, ICollection {
private Dictionary<TKey, HashSet<TValue>> _collection = new Dictionary<TKey,HashSet<TValue>>();
public IEnumerable<TValue> this[TKey key] {
get {
if(!_collection.ContainsKey(key)) return new List<TValue>();
return _collection[key];
}
}
public void Add(TKey key,TValue value) {
if(_collection.ContainsKey(key)) {
_collection[key].Add(value);
}
else {
var hash = new HashSet<TValue>();
hash.Add(value);
_collection.Add(key, hash);
}
}
//***************SNIP irrelevant implementation***************//
}
[ActiveRecord(
DiscriminatorColumn="type",
DiscriminatorType="String",
DiscriminatorValue="1",
Lazy=true)]
public class QAState : LocalBaseModel<QAState> {
[PrimaryKey(PrimaryKeyType.HiLo)]
public virtual int ID { get; protected set; }
[HasMany(Lazy=true)]
public virtual IList<QAState> Children { get; set; }
[BelongsTo(Lazy=FetchWhen.OnInvoke)]
public virtual QAState Parent { get; set; }
public virtual IEnumerable<QAState> QuickStateChain() {
using (new SessionScope()) {
foreach (var x in rQuickStateChain(buildParentDictionary(FindAll()))) {
yield return x;
}
}
}
private IEnumerable<QAState> rQuickStateChain(MultiDictionary<int, QAState> ParentDict) {
yield return this;
foreach (var child in ParentDict[ID]) {
foreach (var c in child.rQuickStateChain(ParentDict))
yield return c;
}
}
private MultiDictionary<int,QAState> buildParentDictionary(QAState[] Nodes) {
var ret = new MultiDictionary<int, QAState>();
foreach(var node in Nodes) {
if (node.Parent == null) continue;
ret.Add(node.Parent.ID, node);
}
return ret;
}
public virtual IEnumerable<QAState> StateChain() {
using (new SessionScope()) {
var root = FindAll().Single(x => x.Parent == null);
foreach (var x in root.rStateChain()) {
yield return x;
}
}
}
private IEnumerable<QAState> rStateChain() {
yield return this;
if (Children != null) {
foreach (var child in Children)
foreach (var c in child.rStateChain())
yield return c;
}
}
//***************SNIP irrelevant implementation***************//
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment