问题
I want to get some data and convert it to a list of objects. From this list I want to select items that are not null and have a specific type. After that I want to convert these object variables to their correct type and return this list as an array.
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();
using this code throws an error at 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?)
My syntax seems to be wrong, all I want to do is
- get this data (returned as a List of objects)
- select all non null values and objects of type ContactEndpoint
- return it as an array
How can I fix it?
回答1:
You can use Enumerable.Cast
or - since you want to filter - Enumerable.OfType
:
So instead of
.Where(item => item != null && item is ContactEndpoint)
.ConvertAll(item => item as ContactEndpoint)
this (since null
values never match any type they are filtered out implicitly by OfType
):
.OfType<ContactEndpoint>()
ConvertAll
is a method of Arrray
or List<T>
回答2:
Try this:
ContactEndpoint[] points = (GetContactInformation(contact, ContactInformationType.ContactEndpoints) as List<object>)
.Where(item => item is ContactEndpoint)
.Cast<ContactEndpoint>()
.ToArray();
回答3:
ContactEndpoint[] points = GetContactInformation(contact,
ContactInformationType.ContactEndpoints)
.Where(item => item != null)
.OfType<ContactEndpoint>()
.ToArray();
You should not need the as List<object>
or the .Select(item => item)
来源:https://stackoverflow.com/questions/52096041/convert-object-list-to-type-array-and-remove-null-values