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

Serdar Şengül picture Serdar Şengül · Feb 6, 2014 · Viewed 11.8k times · Source

I used generic ORM list example.

This is my table.

Person table

Guid
Name
LastName

and this is my struct class.

 public struct PersonItem   // database and class field names are the same
    {
        public Guid   Guid{ get; set; } 
        public string Name { get; set; }
        public string LastName { get; set; }
    }


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

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

I'm using such and no problem but I always have to write field's

public PersonItems GetPersons()
        {
            var query = (from p in _DbEntities.t_Crew
                         select p).ToList();

            if (query != null)
            {
                foreach (var item in query)
                {
                    _PersonItems.Items.Add(new PersonItem
                        {
                            Guid = item.Guid,
                            Name = item.Name,
                            LastName = item.LastName

                        });
                }
            }

            return _PersonItems;

        }   


   public PersonItems GetPersons()
    {
        PersonItems personItems = new 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 ;
    }

error

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

Answer

spajce picture spajce · Feb 6, 2014

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;
    }