我可以一次查询C#对象上的所有布尔属性,查找单个匹配项吗?
想象对象:我可以一次查询C#对象上的所有布尔属性,查找单个匹配项吗?,c#,linq,C#,Linq,想象对象: public class ImaginaryObject { int objectId { get; set; } string name { get; set; } bool b1 { get; set; } bool b2 { get; set; } bool b3 { get; set; } } 是否有任何方法可以编写一个查询,而不命名对象上的任何字段,返回布尔值,如果对象上的任何布尔值为true,则返回true,否则返回false (
public class ImaginaryObject
{
int objectId { get; set; }
string name { get; set; }
bool b1 { get; set; }
bool b2 { get; set; }
bool b3 { get; set; }
}
是否有任何方法可以编写一个查询,而不命名对象上的任何字段,返回布尔值,如果对象上的任何布尔值为true,则返回true,否则返回false
(标记为Linq,因为我怀疑这可能是答案的一部分,如果可能的话)您可以使用GetType()
和GetProperties()
方法从System.Reflection
命名空间动态获取类型对象的详细信息
var booleanProperties = imaginaryObject.GetType()
.GetProperties()
.Where(prop => prop.PropertyType == typeof(Boolean));
foreach(var prop in booleanProperties)
{
if((bool)prop.GetValue(imaginaryObject, null) == true)
return true;
}
或者简单地使用LINQ:
var isAnyTrue= imaginaryObject.GetType()
.GetProperties()
.Where(prop => prop.PropertyType == typeof(Boolean))
.Any(prop => (bool)prop.GetValue(imaginaryObject, null));
您可以使用System.Reflection
命名空间中的GetType()
和GetProperties()
方法动态获取对象所属类型的详细信息
var booleanProperties = imaginaryObject.GetType()
.GetProperties()
.Where(prop => prop.PropertyType == typeof(Boolean));
foreach(var prop in booleanProperties)
{
if((bool)prop.GetValue(imaginaryObject, null) == true)
return true;
}
或者简单地使用LINQ:
var isAnyTrue= imaginaryObject.GetType()
.GetProperties()
.Where(prop => prop.PropertyType == typeof(Boolean))
.Any(prop => (bool)prop.GetValue(imaginaryObject, null));
使用反射来获取属性类型。如果您不想深入研究反射,为什么不添加一个私有属性,该属性是所有其他属性的逻辑OR的结果?就像
bool result=b1 | | b2 | | b3…
每当你有这样一个导致反射方法的需求时,你就会知道你做错了什么。在这种情况下,这些布尔属性属于一个bool[]
(或列表)@mattstrower,那么您的问题似乎缺少上下文。基于反射的答案不能用于在EF中形成IQueryable
的Where
子句,如果这是您的意图。@Mattstrower:那么设计问题就更糟了,您必须修复数据库模型。创建另一个通过外键引用主表的表。它更高效,维护更好,更容易编写可读查询(无论是LINQ还是sql)。实体框架将自动创建允许查询这些布尔值的集合属性。使用反射获取属性类型。如果不想深入研究反射,为什么不添加一个作为逻辑OR结果的私有属性?就像bool result=b1 | | b2 | | b3…
每当你有这样一个导致反射方法的需求时,你就会知道你做错了什么。在这种情况下,这些布尔属性属于一个bool[]
(或列表)@mattstrower,那么您的问题似乎缺少上下文。基于反射的答案不能用于在EF中形成IQueryable
的Where
子句,如果这是您的意图。@Mattstrower:那么设计问题就更糟了,您必须修复数据库模型。创建另一个通过外键引用主表的表。它更高效,维护更好,更容易编写可读查询(无论是LINQ还是sql)。实体框架将自动创建一个集合属性,允许查询这些布尔值。