Search code examples
c#asp.net-4.0system.reflectionfieldinfo

Using System.Reflection to retrieve a list of const string fields


I've created a class of classes (showing one of them) with const string that I want to itarate on.

public static class HTDB_Cols
{
    public sealed class Assistant
    {
        public const string EntryID  = "entryID",
                CustName  = "custName",
                SerialNum  = "serialNum",
                UserName  = "userName",
                Password  = "password",
                EndDate  = "end_date",
                CustID  = "custID",
                TmpCheck  = "tmpCheck",
                Isfamily  = "isfamily",
                Isserver  = "isserver";
    }
}               

public static class DB
{    
    public static void insert(string TableName)
    {
        ColumnsCollection = typeof(HTDB_Cols).GetNestedTypes().Where(f => f.DeclaringType.Name.ToLower().Equals(TableName.ToLower()));
    } 
}

The code above shows my attempt, but even after lots of trial and error I still couldn't get it right.

I want to have a list of all columns as const collection array or list.


Solution

  • var dict = typeof(HTDB_Cols).GetNestedTypes()
                .First(t=>String.Compare(t.Name,TableName,true)==0)
                .GetFields()
                .ToDictionary(f => f.Name, f => f.GetValue(null));
    

    To get a list

    var list = typeof(HTDB_Cols).GetNestedTypes()
                .First(t => String.Compare(t.Name, TableName, true) == 0)
                .GetFields()
                .Select(f => f.GetValue(null) as string)
                .ToList();