sidron
sidron

Reputation: 79

Get field from class using string

public class Class{
    public string First{get;set;}
    public string Second{get;set;}
}

This is my simply class. Then I create a list with this class. I want to use my variable string to get field from this class for example:

var myRecord = new List<class>();
// add...
string myString = "Second";
var somethinf = myRecord.Where(i => i.myString == something)

There is a way to get this field Second from myString

Upvotes: 0

Views: 40

Answers (2)

TVOHM
TVOHM

Reputation: 2742

Avoiding reflection, a simpler approach might be to just make your class wrap a Dictionary:

public class Class
{
    private Dictionary<string, string> _dictionary;

    public Class()
    {
        _dictionary = new Dictionary<string, string>()
        {
            { "First", "Foo" },
            { "Second", "Bar" }
        };
    }

    public string this[string key]
    {
        get { return _dictionary[key]; }
        set { _dictionary[key] = value; }
    }
}

You could then get the data you need using:

var myRecords = new List<Class>();
// ...
string variableString = "Second", valueString = "Foo";
var results = myRecords.Where(x => x[variableString] == valueString);

Upvotes: 0

Christos
Christos

Reputation: 53958

You could make use of reflection to accomplish this:

 var somethinf = myRecord.Where(prop => ((string)typeof(Class).GetProperty("Second").GetValue(prop)) == something);

Please see this fiddle.

Upvotes: 2

Related Questions