c# - 将对象列表转换为类型数组并删除空值

标签 c# linq

我想获取一些数据并将其转换为对象列表。我想从此列表中选择不为空且具有特定类型的项目。之后,我想将这些对象变量转换为正确的类型,并将此列表作为数组返回。

        ContactEndpoint[] points = (GetContactInformation(contact, ContactInformationType.ContactEndpoints) as List<object>)
            .Select(item => item)
            .Where(item => item != null && item is ContactEndpoint)
            .ConvertAll(item => item as ContactEndpoint)
            .ToArray();

使用此代码会在 ConvertAll 处引发错误

'IEnumerable' does not contain a definition for 'ConvertAll' and no extension method 'ConvertAll' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)

我的语法好像不对,我只想做

  • 获取此数据(作为对象列表返回)
  • 选择所有非空值和 ContactEndpoint 类型的对象
  • 将其作为数组返回

我该如何解决?

最佳答案

您可以使用 Enumerable.Cast或者 - 因为你想过滤 - Enumerable.OfType :

所以代替

.Where(item => item != null && item is ContactEndpoint)
.ConvertAll(item => item as ContactEndpoint)

这个(因为 null 值从不匹配它们被 OfType 隐式过滤掉的任何类型):

.OfType<ContactEndpoint>() 

ConvertAllArrray 的一种方法或 List<T>

关于c# - 将对象列表转换为类型数组并删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52096041/

相关文章:

c# - 在 Azure 中无需修改代码即可部署

c# - 如何使用 Swagger 生成选项(CORS)

c# - SQL Server 中的自定义聚合函数与 Linq 中的聚合

c# - 仅对 DbContext 中的一个查询使用选项 IsolationLevel.ReadUncommited

c# - IEnumerable 作为 DataTable 性能问题

C# HtmlAgilityPack 读取非 html 标签

c# - 从 Office 365 发送电子邮件不再支持基本身份验证和 SMTP

linq - 如何使用linq过滤到一组的最大值

linq - 如何使用 LINQ 和连接检索 CRM Guid?

linq - 如何在 Entity Framework 中重用 select 语句?