Richard Ray
Richard Ray

Reputation: 67

Convert List to generic list

I'm trying to convert json data into generic list

string result = e.Result;
JObject o = JObject.Parse(result);
var results = o["Data"];
List<Data> _lst = results.ToList();

but list conversion it's showing error

 'System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>' to 'System.Collections.Generic.List<PhoneApp2.Employee.CandidateManager.Data>'. An explicit conversion exists (are you missing a cast?)  

Upvotes: 0

Views: 910

Answers (1)

Vlad
Vlad

Reputation: 1439

You should convert JToken to Data:

Data CreateData(JToken token)
{
    // some code for creating Data from token.
}

Then you can use it:

var _lst = results.Select(CreateData).ToList();

EDIT

For example your Data class looks like this:

class Data
{
    public string Name { get; set; }

    public int SomeValue {get; set; }
}

Let token have SomeValue and Name keys.

Your CreateData method will be

Data CreateData(JToken token)
{
    return new Data
    {
        Name = token.Value<string>("Name"),
        SomeValue = token.Value<int>("SomeValue")
    }
}

Upvotes: 2

Related Questions