views:

39

answers:

2

With an ASP.NET MVC project I'm working on, I am required to check whether bit variables within a LINQ-To-SQL class are true. So far, After checking whether or not each variable is true or false, I then push the value of the field into a List and return it like so:

public List<String> GetVarList() {
    List<String> list = new List<String>();

    if (fields.SearchBar) {
        list.Add("SearchBar");
    }

    if (fields.SomeField) {
        list.Add("SomeField");
    }

    return list;
}

This, to me, doesn't seem to be the fastest or easiest way to do it.

I was wondering its possible to somehow be able check the value of the variable dynamically from an array of strings by looping through them with either a for or a foreach loop. For instance:

public List<String> GetVarList() {
    String[] array = {"SearchBar", "SomeField"};
    List<String> list = new List<String>();

    foreach (String field in array) {
        // Check whether or not the value is true dynamically through the array
    }

    return list;
}

Thanks for any suggestions!

A: 

You can use reflection:

public List<String> GetVarList() {
    String[] array = {"SearchBar", "SomeField"};
    List<String> list = new List<String>();
    var type=fields.GetType();
    foreach (String field in array) {
        var prop=type.GetProperty(field);
        if ((bool)prop.GetValue(fields,null))
            list.Add(field);
    }

    return list;
}

From your question is not clear if SearchBar, SomeFields etc. are fields or properties. If they are fields, change the code accordingly (use GetField() instead of GetProperty())

Andrea Parodi
A: 

Certainly, you can use reflection for something like this:

private bool ValueWasSet(string propertyName)
{
    var property = fields.GetType().GetProperty(propertyName);
    return (bool)property.GetValue(fields, null);
}

public List<string> GetVarList()
{
    return new [] {"SearchBar", "SomeField"}
        .Where(ValueWasSet)
        .ToList();
}

It is a very straight-forward solution to what you want to do, assuming you have a lot of items to look through.

CAVEAT: This is NOT faster than your code. Your code is much faster than this... but if you want to do it more dynamically, you have to pay a slight perf price.

Brian Genisio