IlDrugo
IlDrugo

Reputation: 2069

Can't create list of object in nested list with linq

I've developed a dll that allow me to use some method of my API. All working pretty well, but now I have a problem with linq. In particular I usually store all the results returned from the api in a list of object. So I can iterate through of it and get each item separated. Now I have this class:

public class Agent
{
        public int id { get; set; }
        public string name { get; set; }
}

public class RootObject
{
        public List<Agent> agent { get; set; } 
}

I deserialize the json like this:

var obj = JsonConvert.DeserializeObject<RootObject>(responseText);
return obj.Select(o => o.agent).ToList();

now I can deserialize the json correctly 'cause is a list of Agent but I can't use the method to return a list of object:

return obj.Select(o => o.agent).ToList();

the .Select is underlined in red, and the compiler tell me:

Agent.RootObject does not contain a definition for Select

if instead I use: var obj = JsonConvert.DeserializeObject<List<RootObject>>(responseText);

all the return line is underlined in red:

Can't convert System.Collections.Generic.List in System.Collections.Generic.List

so how can I fix this problem?

Upvotes: 0

Views: 103

Answers (1)

Tom
Tom

Reputation: 2390

Select is an IEnumerable extension method, you cannot Select from obj unless it implements IEnumerable. In your case, you probably just need return obj.agent;.

Your 2nd attempt is showing an error on the whole line because your return type is most likely wrong. We would need to see your entire method, especially the signature, to tell you the exactly issue.

Upvotes: 3

Related Questions