[英]Get IList item by concrete type using Linq
So I have the following: 所以我有以下几点:
public IList<ISignupStepViewModel> Steps { get; set; }
An example of a concrete implementations of ISignupStepViewModel would be: ISignupStepViewModel的具体实现的示例为:
public class SignupStepBillingViewModel : ISignupStepViewModel
public class SignupStepPricingViewModel : ISignupStepViewModel
I initialize Steps
with concrete classes that implement ISignupStepViewModel
with the following: 我用实现ISignupStepViewModel
具体类初始化以下Steps
:
Steps = typeof (ISignupStepViewModel)
.Assembly
.GetTypes()
.Where(t => !t.IsAbstract && typeof (ISignupStepViewModel).IsAssignableFrom(t))
.Select(t => (ISignupStepViewModel) Activator.CreateInstance(t))
.ToList();
I would like to now get a specific item in IList<ISignupStepViewModel> Steps
with Linq, something like: 我现在想在Linq的IList<ISignupStepViewModel> Steps
获得特定项,例如:
var billingStep = (SignupStepBillingViewModel)signupObj.Steps.FirstOrDefault(t => typeof(t) == SignupStepBillingViewModel);
Is there a way to do this? 有没有办法做到这一点? Currently I am getting the error "Class name is not valid at this point" on SignupStepBillingViewModel in bold: 当前,SignupStepBillingViewModel上以粗体显示错误“类名此时无效”:
(SignupStepBillingViewModel)signupObj.Steps.FirstOrDefault(t => typeof(t) == SignupStepBillingViewModel ); (SignupStepBillingViewModel)signupObj.Steps.FirstOrDefault(t => typeof(t)== SignupStepBillingViewModel );
尝试使用关键字: is代替: typeof(t)== SignupStepBillingViewModel
var billingSteps = signupObj.Steps.Where(t => t is SignupStepBillingViewModel).Select(t => (SignupStepBillingViewModel)t).ToList();
尝试这个:
signupObj.Steps.FirstOrDefault(t => t.GetType() == typeof(SignupStepPricingViewModel)) as SignupStepPricingViewModel;
感谢@JonSkeet在评论中建议的所有帮助和最简单的解决方案是:
var billingStep = Steps.OfType<SignupStepBillingViewModel>().First();
This code 这段代码
Steps.Select(t => typeof(t) == SignupStepBillingViewModel);
will produce a collection of bool
values which you then try to case to your object. 会产生bool
值的集合,然后您尝试对对象进行大小写。 Try this: 尝试这个:
var billingStep = (SignupStepBillingViewModel)Steps.FirstOrDefault(t => typeof(t) == SignupStepBillingViewModel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.