1

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?

3 Answers 3

6

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@MHComputech: yes, since null values never match any type they are filtered out.
2

Try this:

ContactEndpoint[] points = (GetContactInformation(contact, ContactInformationType.ContactEndpoints) as List<object>)
            .Where(item => item is ContactEndpoint)
            .Cast<ContactEndpoint>()
            .ToArray();

1 Comment

I think using .OfType<ContactEndpoint>() is the better solution but I upvoted yours too :)
1
    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)

2 Comments

You do not need the Where since the OfType already sorts out null values.
I know, I saw Tims answer. I probably would leave it in in Production. Just for readability, don't leave questions for the reader.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.