Sunday, April 19, 2009

Enum, LINQ, and Lookup Tables in C#/SQL Server

Three options:

1. Auto generate ENUM from a lookup table (still have to compile). Here's some helpful links:

2. Just use a dataset object directly (but is a bit ambiguous when coding).

3. Use something that implements IDictionary. This is not as nice as an Enum, but you get the dynamic benefit and it's not as ambiguous when you code. Here's an example:

//put this in a static class, singleton, abstract class, or whatever fits your need

private SortedList _CriteriaItem;

//get data from database and iterate over the dataset to populate the list
public void Add(object Key, object Value)
{
_CriteriaItem.Add(Key, Value);
}

public String GetDescriptionByCode(String key)
{
if (_Item.ContainsKey(key))
{
return _Item[key].ToString();
}

return "";
}


public String GetCodeByDescriptionBy(String description)
{
if (_Item.ContainsValue(description))
{
foreach (String key in _Item.Keys)
{
if (_Item[key].ToString() == description)
{
return key.ToString();
}
}
}

return "";
}

No comments: