You can't use LINQ directly to iterate through the properties of an object since there isn't an enumeration of the properties of the object available on the object. You can, however, use Reflection to get at the properties of an object. LINQ may come in handy when looking through these to find the appropriate object for your placeholder.
public Dictionary<string,object>
ValuesForPlaceHolders( object obj,
IEnumerable<string> placeHolders )
{
var map = new Dictionary<string,object>();
if (obj != null)
{
var properties = obj.GetType().GetProperties();
foreach (string placeHolder in placeHolders)
{
var property = properties.Where( p => p.Name == placeHolder )
.SingleOrDefault();
if (property != null)
{
map.Add( placeHolder, property.GetValue( obj, null ) );
}
}
}
return map;
}
EDIT: The above sample was written to illustrate how LINQ could be used. My preference actually is using a helper method to get values by name. Note that the method below assumes that the property exists, but could easily be modified to return null when the property doesn't exist. In my usage my calls to it are verified by unit tests so I don't bother with the extra check.
public static class TypeHelper
{
public static object GetPropertyValue( object obj, string name )
{
return obj == null ? null : obj.GetType()
.GetProperty( name )
.GetValue( obj, null );
}
}