【发布时间】:2019-07-08 15:15:48
【问题描述】:
我有一个名为eventQueue 的对象列表,其中存储了在后台执行的任务产生的所有事件。现在,我需要处理这个列表,从中提取特定事件。我想主要使用 LINQ 来提高代码的可读性(我不想编写多个 foreach),我的问题是我不完全知道如何进行。假设我有一个自定义 EventArgsnamed FirstEventArgs 的多个实例,我想从列表中提取一个特定的实例,做一个我会写的 foreach
foreach(object o in eventQueue)
{
if( o is FirstEventArgs)
{
FirstEventArgs ev = o as FirstEventArgs ;
if( ev.MyProperty == desiredValue)
{
// you got it
}
}
}
目前我可以在 LINQ 中编写以下代码
FirstEventArgs ev = eventQueue.Where(x => x.GetType() == typeof(FirstEventArgs )).SingleOrDefault() as FirstEventArgs;
我的问题是。我如何修改前面的以在 Where if x is of type object 中添加条件ev.MyProperty = desiredValue?
【问题讨论】: