Thursday, June 12, 2008

Trie Algorithm for Autocomplete and Suggest word

Currently I try using Trie for Suggest and Autocomplete algorithm.

public List<string> Suggest2(string str)
{
List<String> result = new List<String>();
TrieNode curr = root;
foreach (char c in str.Trim().ToLower().ToCharArray())
{
curr = curr.GetChild(c);
if (curr == null)
return result;
}

Suggest2(curr, new StringBuilder(str), result);
return result;

}

public void Suggest2(TrieNode curr,StringBuilder sbTemp, List<string> result)
{
if (curr == null) return;
if (curr.IsEnd) result.Add(sbTemp.ToString());

foreach (char c in curr.Childs.Keys)
{
sbTemp.Append(c);
Suggest2(curr.Childs[c], sbTemp, result);
sbTemp.Length--;
}
}



Any Suggestion to improve this algorithm except changing String to StringBuilder ?

Friday, June 6, 2008

IDisposable Pattern in .NET

In some cases we also need to implement IDisposable pattern in our code.

For example, If you have unmanaged objects such as (File, Image, TCP Connection, etc) or you want to make sure that you have closed your connection / web service.

Here is the code

#region IDisposable Pattern
/// <summary>
///
Desctructor in VB.NET - Finalize
/// It will be called by Garbage Collector
/// or you may force GC by calling GC.Collect()
/// </summary>
~MyClass()
{
//only dispose unmanaged obj, for managed obj,
//it probably already been clear by GC,
//so we cannot called it again.
Dispose(false);
}
/// <summary>
///
Will be called when you use 'using'
/// keyword or implicitly called by you obj.Dispose()
/// </summary>
public void Dispose()
{
Dispose(true);
//tell GC not to run Desctrutor,
//because it has been called implicitly
GC.SuppressFinalize(this);
}

/// <summary>
///
Dispose Unmanaged and manage
/// </summary>
/// <param name="bDisposeManaged">
///
true - dispose unmanaged and managed code as well
/// fase - dispose only and unmanaged
/// </param>
protected virtual void Dispose(bool bDisposeManaged)
{
try
{
if (bDisposeManaged)
{
//TODO: dispose managed code
//Such as(Service, connection, etc)
if (_ServiceUser != null)
{
try
{
_ServiceUser.Dispose();
}
catch { }
}
}
//TODO: dispose unmanaged code
//such as (File, Bitmap / Image, TCP Connection, etc)
}
catch{}
}
#endregion