1 Replies - 6431 Views - Last Post: 05 January 2012 - 12:23 PM Rate Topic: -----

#1 ItIntern3  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 97
  • Joined: 14-July 10

LINQ Return Generic List from Method

Posted 05 January 2012 - 11:16 AM

Hi all,

I am trying to return a generic list from a method and am having a bit of trouble with the syntax. Here's what I have:

class GenList<T>
    {
        private List<T> list;
        private SampleEntities context = new SampleEntities();

        public GenList(List<T> contactList)
        {
            list = contactList;
            populateList();
        }

        public List<T> populateList()
        {
            var contacts = (from c in context.Contacts select new T{ c.FirstName, c.LastName };
            list = contacts.ToList(); 

            return list;
        }
    }


I am creating an instance from the main method:

 class Program
    {
        static void Main(string[] args)
        {
            List<Contact> contactList = null;
            GenList<Contact> list = new GenList<Contact>(contactList); 

            foreach (Contact c in list)
                Console.Write(c.FirstName + "\n");

            Console.ReadLine();
        }

    }



I am getting an error on line:
var contacts = (from c in context.Contacts select new T{ c.FirstName, c.LastName };


reading: cannot initialize T because it does not implement Collections.Generic.IEnumerable.

If anyone has any ideas on how to get rid of this error it would be greatly appreciated!
Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: LINQ Return Generic List from Method

#2 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,957
  • Joined: 21-March 08

Re: LINQ Return Generic List from Method

Posted 05 January 2012 - 12:23 PM

Your generic method isn't really generic. Even though you are using T, you are not using it correctly.

Look at your logic. Even though you are accepting any type(that's what T means), you are using it like it's a Contact(FirstName and LastName). You are even populating the list by looking at the Contact table. How is that generic? What if you used string as the type instead of Contact. It wouldn't work.

What are you trying to accomplish? Why not just return a type-safe List<Contact>?

Looks like you are trying to over-complicate something that should be fairly easy.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1