一個簡單的解決方案是一個使用LINQ的Select
方法:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string Name { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class PersonCollection : List<Person>
{
public object[] GetValues(string propertyName)
{
if (propertyName == "Name")
{
return this.Select(p => p.Name).ToArray();
}
else if (propertyName == "Property1")
{
return this.Select(p => p.Property1).ToArray();
}
else if (propertyName == "Property2")
{
return this.Select(p => p.Property1).ToArray();
}
// best way to implement this method?
return null;
}
}
您還可以使用表達式樹以允許類型安全的訪問器lambda被用作參數:
public object[] GetValues(Expression<Func<Person, object>> propertyNameExpression)
{
var compiledPropertyNameExpression = propertyNameExpression.Compile();
if (propertyNameExpression.Body.NodeType == ExpressionType.MemberAccess)
{
return this.Select(compiledPropertyNameExpression).ToArray();
}
throw new InvalidOperationException("Invalid lambda specified. The lambda should select a property.");
}
然後,您可以將此用作follo WS:
var personNames = personCollection.GetValues(p => p.Name)
感謝您的解決方案。 –
@DJ不客氣。 –