Home > Software design >  How to convert from List<object> to List<T> in c#?
How to convert from List<object> to List<T> in c#?

Time:09-08

I have a Class:

public class Element
{
   public List<object> objects { get; set; }
}

And a Class:

public class Node
    {
        public long id { get; set; }
    }

I pass in a List<object> nodes. So is there any way I can convert those List<object> objects to List<Node> nodes?

I tried this way but it doesn't work List<Node> nodes = objects.Select(s => (nodes)s).ToList();

CodePudding user response:

Try this: where listObject is the List<object>

List<Node> newlist = listObject.Cast<Node>().ToList();

CodePudding user response:

Your JSON is this:

{  "type": "way",
  "id": 1000828751,
  "nodes": [
    9238280575,
    9238280590,
    9238280589,
    9238280576,
    9238280592,
    9238280577,
    9238280578,
    9238280575
  ],
  "tags": {
    "amenity": "fire_station",
    "name": "Đội Cảnh sát PCCC & CNCH quận Long Biên"
  }
}

When I use https://json2csharp.com to create the C# classes I get this:

public class Root
{
    public string type { get; set; }
    public int id { get; set; }
    public List<object> nodes { get; set; }
    public Tags tags { get; set; }
}

public class Tags
{
    public string amenity { get; set; }
    public string name { get; set; }
}

And that does successfully deserialize your JSON, but that's where you're at, trying to convert List<object> to List<long>. However, the tool could have done better had it defined nodes like this:

public class Root
{
    ...
    public List<long> nodes { get; set; }
    ...
}

That now works without any further code changes.

  •  Tags:  
  • c#
  • Related