使用帮助类通过名称动态访问属性怎么样(可以扩展为使用一些缓存):
public class ObjectUtils
{
public static object GetPropertyByName(object obj, string name)
{
if (obj == null)
{
return null;
}
PropertyInfo propInfo = obj.GetType().GetProperty(name);
if (propInfo == null)
{
return null;
}
object value = propInfo.GetValue(obj, null);
return value;
}
}
然后得到这样的数据:
List<dynamic> list = new List<dynamic>();
list.Add(new { Col1 = "AB", Col2 = 23 });
list.Add(new { Col1 = "CD", Col2 = 23 });
list.Add(new { Col1 = "AB", Col2 = 5 });
list.Add(new { Col1 = "EF", Col2 = 9 });
string[] columns = new string[] { "Col1", "Col2" };
foreach (string column in columns)
{
var elems = list.Select(d => ObjectUtils.GetPropertyByName(d, column)).Distinct().ToList();
// elems will be "AB", "CD", "EF" for Col1
// and 23, 5, 9 for Col2
}
如果无法编译,请确保添加对 Microsoft.CSharp 的引用