leo*_*n22 0 c# linq dictionary
我使用以下代码将我的类的公共属性转换为Dictionary:
public static Dictionary<string, object> ClassPropsToDictionary<T>(T classProps)
{
return classProps.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(classProps, null));
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我不想要类的引用成员:
public class Unit
{
public virtual string Description { get; set; } // OK
public virtual Employee EmployeeRef { get; set; } // DONT WANT THIS
}
Run Code Online (Sandbox Code Playgroud)
我需要哪个绑定标志来避免EmployeeRef成员?
谢谢
Where与IsClass财产一起使用:
classProps
.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => !x.PropertyType.IsClass)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(classProps, null));
Run Code Online (Sandbox Code Playgroud)
没有BindingFlag.大多数 BindingFlags与访问修饰符和继承层次结构等相关.它们不能指定为消除值类型或引用类型.如果您不想消除内置类型,string然后声明一个数组,请将所有类型放入其中,然后使用Contains:
var allowedTypes = new [] { typeof(string), ... };
.Where(x => !x.PropertyType.IsClass || allowedTypes.Contains(x.PropertyType))
Run Code Online (Sandbox Code Playgroud)
由于大多数内置类型都位于System命名空间中,因此您还可以简化:
.Where(x => !x.PropertyType.IsClass ||
x.PropertyType.AssemblyQualifiedName.StartsWith("System"))
Run Code Online (Sandbox Code Playgroud)