[英]C# - Help with LINQ
我需要检查一个类中是否存在某个属性。 请参阅有问题的LINQ查询。 对于我的生活,我不能让编译器开心。
class Program
{
static void Main(string[] args)
{
ModuleManager m = new ModuleManager();
IModule module = m.FindModuleForView(typeof(HomeView));
Console.WriteLine(module.GetType().ToString());
Console.ReadLine();
}
}
public class ModuleManager
{
[ImportMany]
public IEnumerable<Lazy<IModule>> Modules { get; set; }
[ImportMany]
public IEnumerable<Lazy<View>> Views { get; set; }
public ModuleManager()
{
//An aggregate catalog that combines multiple catalogs
var catalog = new AggregateCatalog();
//Adds all the parts found in the same assembly as the Program class
catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
//Create the CompositionContainer with the parts in the catalog
_container = new CompositionContainer(catalog);
//Fill the imports of this object
try
{
this._container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
public IModule FindModuleForView(Type view)
{
//THIS IS THE PROBLEM
var module = from m in Modules
where (
from p in m.Value.GetType().GetProperties()
where p.GetType().Equals(view)
select p
)
select m;
}
public CompositionContainer _container { get; set; }
}
public interface IModule
{
}
[Export]
public class HomeModule : IModule
{
public HomeModule()
{
}
[Export]
public HomeView MyHomeView
{
get
{
return new HomeView();
}
set
{
}
}
}
public class HomeView : View
{
}
public class View
{
}
GetProperties()返回PropertyInfo对象的数组。 您对p.GetType()的调用总是返回typeof(PropertyInfo) - 从不传递您传入的“视图”类型。
你可能想要这个:
from p in m.Value.GetType().GetProperties()
where p.PropertyType.Equals(view)
select p
编辑
正如Robert指出的那样,确定上述查询是否返回任何属性的逻辑也是错误的。 一个简单的方法是查看是否有任何从子查询返回的内容:
var module = from m in Modules
where (
from p in m.Value.GetType().GetProperties()
where p.PropertyType.Equals(view)
select p
).Any()
select m
请记住,该查询可能会返回多个模块。 您可能希望从结果中返回.First()。
where
关键字需要一个返回布尔条件的谓词,但是您提供的子查询返回一个IEnumerable
。 你可以重写你的子查询,以便它返回一个实际的布尔条件?
您可以使用FirstOrDefault()
扩展方法将其转换为布尔结果。 如果没有记录,此方法将返回null
。 所以这应该工作(未经测试):
where ( from p in m.Value.GetType().GetProperties()
where p.PropertyType.Equals(view)
select p ).FirstOrDefault() != null
内部查询应返回bool
,但返回PropertyInfo
。
我没有测试过这个,但我想你想要的东西:
var module = (from m in Modules
where m.Value.GetType().GetProperties()
.Select(p => p.PropertyType).Contains(view)
select m).FirstOrDefault();
将Enumerable.Any
建议纳入另一个答案:
var module = (from m in Modules
where m.Value.GetType().GetProperties()
.Any(p => p.PropertyType.Equals(view))
select m).FirstOrDefault();
即使您可以查询您的查询,我也不认为这是将您的模型与您的视图相关联的好方法。 我建议创建一个新问题,详细说明你要做什么(以及为什么),询问如何在模型和视图之间创建关联/链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.