Luis Valencia
Luis Valencia

Reputation: 33988

How to get all properties with an specific name and create a List<KeyValuePair<string,string>>

I need to do with some kind of reflection the following:

  1. Get all property names from an object, and select only the ones with the word Role on it.
  2. Once I have all properties, create a List<KeyvaluePair<string,string>>, where the key will be the property name and the value will come from the object property.

I guess this can be done easily with linq and/or lambda expressions but no idea how.

The code I have so far is:

SyncJobs_Result job = (SyncJobs_Result)entity.Entity;
var properties = typeof(SyncJobs_Result ).GetProperties(BindingFlags.Static | BindingFlags.Public).Select(p => p.Name.Contains("Role"));

How can I build a List> out of this? with the key being the column or property name and the value being the property value

Upvotes: 0

Views: 236

Answers (1)

Jakub Konecki
Jakub Konecki

Reputation: 46008

SyncJobs_Result job = (SyncJobs_Result)entity.Entity;
var properties = typeof(SyncJobs_Result)
    .GetProperties(BindingFlags.Static | BindingFlags.Public)
    .Where(p => p.Name.Contains("Role") && p.PropertyType == typeof(string))
    .Select(p => new KeyValuePair<string, string>(p.Name, p.GetValue(job, null) as string))
    .ToList();

Writing without Visual Studio so there may be a syntax error or two, but hopefully this will point you in the right direction.

Upvotes: 3

Related Questions