We help IT Professionals succeed at work.

IEnumerable<T> to a List<T>

sbornstein2
sbornstein2 asked
on
224 Views
Last Modified: 2017-03-07
Hello all,

I have the following class currently:
  [Serializable]
    [CollectionDataContract(Name = "Customers", ItemName = "Customer", Namespace = "")]
    public class Customers : List<Customer>
    { }

    [DataContract(Namespace = "")]
    public class Customer
    {
        [Key]
        [DataMember]
        public int CustomerID { get; set; }
        [DataMember]
        public string CustomerCode { get; set; }
        [DataMember]
        public string CustomerName { get; set; }
    }

Open in new window


I then have an IEnumerable coming back from the DapperORM tool that comes back as IEnumerable<Customer>.  How do I handle this I am getting issues everytime on casts etc?

That code sample is:
  public Customers  GetCustomers()
        {
            using (conn)
            {
                if (filters.Count() == 0)
                { 
                    return conn.GetList<Customer>(); //this needs to be changed to pass the Customers list.
                }
            }
        }

Open in new window


I can't change the dapper side it needs a <T> passed and returns an IEnumerable<Customer> in this case.
Comment
Watch Question

Nitin SontakkeDeveloper
CERTIFIED EXPERT

Commented:
Can yo not say:

IEnumerable<Customer> custs = conn.GetList<Customer>();

Open in new window


And then....

return custs.ToList();

Open in new window

Author

Commented:
Dapper passes back a generic IEnumerable it seems.   So the error for example when I do as you are saying shows:

Cannot implicitly convert type 'Systems.Collections.GenericList<Customer>' to 'Customers '.  An explicit conversion exists (are you missing a Cast).  

I have tried casting and it still does it all the time different similar errors.

Author

Commented:
If I pass it as an IEnumerable<Customer> it seems to work just fine.
Nitin SontakkeDeveloper
CERTIFIED EXPERT

Commented:
If it is not much of the problem change

public Customers  GetCustomers()

Open in new window

to

public List<Customer>  GetCustomers()

Open in new window

I personally don't see any reason why it should be a problem.

Author

Commented:
I guess the stupid question is then how do I get it to be a CollectionDataContract list as I am showing in the first post.   I need that serializable object.

Author

Commented:
It is in a different namespace wondering if that is the issue
Developer
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
You are a life saver...:).  Thanks so much that was perfect.  Now I just need to figure out how to get rid of the xmlns:i="http://www.w3.org/2001/XMLSchema-instance" in the header of the XML.   Thanks so much appreciate it.