Home > Back-end >  Cant Convert List of Type<T> to List of Type<T>
Cant Convert List of Type<T> to List of Type<T>

Time:08-14

I get told I cannot convert From System generic List to a List of the Exact same type:

 public JsonResult People()
        {
            var test = new List<People>();
            var page = "";
            var pageNumber = "1";
            SharpEntityResults<People> results = null;

            while (page != "" || page != null)
            {
               results = starCore.GetAllPeople(pageNumber);
                List<People> x = results.results;
                test.Add(x);
            }
 public class People : SharpEntity
  public SharpEntityResults<People> GetAllPeople(string pageNumber = "1")
        {
            SharpEntityResults<People> result = GetAllPaginated<People>("/people/", pageNumber);

            return result;
        }

Not sure why I cant add to my test List when both are of the same type

The Error States:

cannot convert from System.Collections.Generic>List<ProjectName.Entitites.People> to Projectname.Entitites.People

CodePudding user response:

test is a List<People> and x is also a List<People>, so you are trying to add a list to a list. Try to use AddRange instead.

This way you will add all items from x to the list test.

CodePudding user response:

You've a mistake in your code.

List<People> x holds objects of type People, if you want to store x in test you need it to be of type List<List<People>> or List<IEnumerable<People>> if you want to add content of x to test you can do test.AddRange(x) this will put / add content of X to the list of Test.

Examples of how to fix this with left hand type declaration for clarity.

For Storing Content of X in Test:

 public JsonResult People()
    {
        List<People> test = new List<People>();
        var page = "";
        var pageNumber = "1";
        SharpEntityResults<People> results = null;

        while (page != "" || page != null)
        {
           results = starCore.GetAllPeople(pageNumber);
            List<People> x = results.results;
            test.AddRange(x);
        }

If you want to store Lists then your code will look like this.

public JsonResult People()
    {
        List<IEnumerable<People>> test = new List<List<People>>();
        var page = "";
        var pageNumber = "1";
        SharpEntityResults<People> results = null;

        while (page != "" || page != null)
        {
           results = starCore.GetAllPeople(pageNumber);
            List<People> x = results.results;
            test.Add(x);
        }

In that case you'll have for each entry a List

  •  Tags:  
  • c#
  • Related