LINQ and Reflecting Object Properties
6/3/2008 1:00:18 PM
In working on a recent project over the weekend I decided to switch to .NET 3.5. I haven't implemented OR/M with LINQ yet so I decided to re-write some of the class library functionality (and existing Data Access Layer) using LINQ, lambda's, and other syntactical sugar. Keep in mind this is a personal project so I can spend some time wasting time!
One of my original methods in the DAL is called Create Parameters. This simply takes an object as a parameter, iterates the properties and creates a SqlParameter and adds it to a List<T>.
public
static List<SqlParameter> CreateParameters(object input)
{
List<SqlParameter> parameters = new List<SqlParameter>();
foreach (PropertyInfo p in input.GetType().GetProperties())
parameters.Add(new SqlParameter(p.Name, p.GetValue(input, null)));
return parameters;
}
Pretty basic. With new C# syntax this can be reduced to one line a la:
public
static IEnumerable<SqlParameter> CreateParameters(object input)
{
return input.GetType().GetProperties().Select(p => new SqlParameter(p.Name, p.GetValue(input, null)));
}
You will noticed that I changed to IEnumerable<SqlParameter>. It can just as easily be converted to List<SqlParameter> by using the ToList extension method.
public
static List<SqlParameter> CreateParameters(object input)
{
return input.GetType().GetProperties().Select(p => new SqlParameter(p.Name, p.GetValue(input, null))).ToList();
}
It should also be worth mentioning that I prefer the above method's syntax over that of the traditional LINQ syntax:
public static List<SqlParameter> CreateParameters(object input)
{
return (from p in input.GetType().GetProperties() select new SqlParameter(p.Name, p.GetValue(input, null))).ToList();
}
I probably won't have much use for these methods after implementing LINQ-to-SQL as it provides a pretty braindead process to CRUD data.
C#,
LINQ
