How to convert LINQ query result to list and return generic List?

回眸只為那壹抹淺笑 提交于 2019-12-06 12:33:04

Try this

 public PersonItems GetPersons()
    {
        PersonItems personItems = new PersonItems();

        var query = (from p in _DbEntities.t_Person
                    select new PersonItems 
                    {
                        test = p.SomeName,
                        //Other Stuff
                        //...
                    }).ToList();
       return query;
    }

Comparing to the other version of your GetPersons() method, I think this line :

personItems = query.ToList();

should've been this way instead :

personItems.Items = query.ToList();

Update regarding the latest error. You can't assign list of t_Person to Item property which is of type list of PersonItem. Hence, your query need to be adjusted to return list of PersonItem :

var query = from p in _DbEntities.t_Person
            select new PersonItem
                        {
                            Guid = p.Guid,
                            Name = p.Name,
                            LastName = p.LastName
                        };

or other option is to change definition of Item property to list of t_Person :

public List<t_Person> Items { get; set; }

Cannot implicitly convert type System.Collections.Generic.List' to PersonData.PersonItems'

Above error says that you are trying to convert generic list to PersonItems.

So at this line, query.ToList() code returns List<PersonItem> not the PersonItems

    var query = from p in _DbEntities.t_Person
                select p; >> this here query I need to convert linq query result to list

   personItems = query.ToList();
   return personItems ;

So thats the reason above line of code fails.

What about this? Change .ctor of PersonItems:

public struct PersonItems
{
    public PersonItems(List<PersonItem> items)
    {
        Items = items;
    }

    public List<PersonItem> Items { get; set; }
 }

And then method GetPersons():

public PersonItems GetPersons()
{    
    return new PersonItems(_DbEntities.t_Person.ToList());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!