I totally agree with @Patrick and his preferred way over mine.
but if you say you are not using C # 6.0, then you can use the code you wrote. I just use a param loop, yield return and one foreach
private static IEnumerable<string> GetPropertyName<TObj, TProp>(params Expression<Func<TObj, TProp>>[] propCollection) { foreach (var prop in propCollection) { var expression = prop.Body as MemberExpression; if (expression != null) { var property = expression.Member as PropertyInfo; if (property != null) { yield return property.Name; } } yield return string.Empty; } }
UPDATE
First, ask you to specify the type of the object over and over, which means you need to provide the full length expression again.
Try below, it will ask you to specify the property as much as you want in only one expression.
public static IEnumerable<string> GetPropertiesName<TObj, TProp>(Expression<Func<TObj, TProp[]>> prop) { var array = (prop.Body as NewArrayExpression); var exp = array == null ? null : array.Expressions; if (exp != null) { //var expArr = (prop.Body as NewArrayExpression).Expressions; foreach (var oneProp in exp) { Expression onePropExp; if (oneProp.GetType() == typeof (UnaryExpression)) { onePropExp = (oneProp as UnaryExpression).Operand; } else { onePropExp = oneProp; } var property = (onePropExp as MemberExpression).Member as PropertyInfo; if (property != null) { yield return property.Name; } yield return string.Empty; } } yield return string.Empty; }
You can call it like this:
var propNames = GetPropertiesName((AllSubsTransAndDevices d) => new[] { d.CurrentDriverId, d.GPSDevicesId, d.TransporterId });
source share