如何过滤掉查询中的项目?

时间:2016-06-03 12:09:51

标签: c# linq task-parallel-library

ReadSensorsAsync有时会返回null Result

 var tasksRead = Enumerable.Range(3, 35).Select(i => ReadSensorsAsync(i));
 var tasksRecord = tasksRead.Select(x => RecordReadingAsync(x.Result));

如何在第二次查询中过滤掉这些任务,我只处理非空项?

2 个答案:

答案 0 :(得分:4)

您只需在第二个语句中添加Where:

 var tasksRead = Enumerable
   .Range(3, 35)
   .Select(i => ReadSensorsAsync(i));

 var tasksRecord = tasksRead
   .Where(x => x.Result != null)
   .Select(x => RecordReadingAsync(x.Result));

答案 1 :(得分:1)

试试这个:

 var tasksRecord = from tr in Enumerable.Range(3, 35).Select(ReadSensorsAsync)
                       where tr != null select RecordReadingAsync(tr.Result);