0

I am returning a list of codes called AllCodes from a SQL database. Basic schema like:

id | countrycode | refprint | refscan | reffax 
1 . US . 123 . 234 . 345

I have a method which should needs to return a a value based on a matching countrycode and whatever column I need from that result.

Here is the method (not working offcourse) but not sure how to achieve this kind of thing with c#

  private string GetServiceCode(string cc, string name)
    {
        var code = AllCodes.Where(x => x.CountryCode == cc).FirstOrDefault();
        if (code != null)
        {
            // I want to return whatever {name} is, not code.name
            // so if name = "refprint" I want to return code.refprint
            return code.{name};
        }
    }

  // Example:
  GetServiceCode("US","refprint"); // Would return 123
2
  • you could look at Dynamic Linq - then it would be .Select(name) Commented Sep 12, 2016 at 12:58
  • You say list, but are you really using a dictionary? Commented Sep 12, 2016 at 13:09

2 Answers 2

2

You could achieve this with reflection:

if (code != null)
{
    PropertyInfo pi = code.GetType().GetProperty(name);
    if (pi == null) return string.Empty;
    object v = pi.GetValue(code);
    if (v == null) return string.Emtpy;
    return v.ToString();
}

With GetProperty() you can get a PropertyInfo for the property named name. Then you can use GetValue() to get the value of the property for a specific instance (code in your case).

In C#6 you could shorten the code to

return code.GetType().GetProperty(name)?.GetValue(code)?.ToString() ?? string.Empty;
Sign up to request clarification or add additional context in comments.

Comments

0

How about using a lambda:

private string GetServiceCode<T>(string cc, Action<T> action)
{
    var code = AllCodes.Where(x => x.CountryCode == cc).FirstOrDefault();
    if (code != null)
    {
        return action(code);
    }
}

// Example:
GetServiceCode("US",(code)=> Console.WriteLine(code.refprint) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.