Linq – Getting error: ‘System.Collections.Generic.IEnumerable‘ does not contain a definition for ‘ToList’

c#-3.0linq

I am doing the below

List<A> lstA = new List<A>();
            Enumerable.Range(1, 10).ToList().ForEach(i => lstA.Add(new A { Prop1 = i, Prop2 = "Prop2" + i.ToString() }));

            List<B> lstB = new List<B>();
            Enumerable.Range(1, 10).ToList().ForEach(i => lstB.Add(new B { Prop1 = i, Prop3 = DateTime.Now }));

            var res = (from a in lstA
                       join b in lstB on a.Prop1 equals b.Prop1
                       select new
                       {
                           Prop1 = a.Prop1
                           ,
                           Prop2 = a.Prop2
                           ,
                           Prop3 = b.Prop3
                       }).ToList<C>();

Means the combined result want to store in List.

At that time getting the error

'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments

How to do so?

class A
    {
        public int Prop1 { get; set; }
        public string Prop2 { get; set; }
    }

    class B
    {
        public int Prop1 { get; set; }
        public DateTime Prop3 { get; set; }        
    }

    class C
    {
        public int Prop1 { get; set; }
        public string Prop2 { get; set; }
        public DateTime Prop3 { get; set; }
    }

Thanks

Best Answer

You're creating a sequence of a new anonymous type, and trying to call ToList<C> on it. That won't work. The simple solution is to change your query to create a sequence of C:

var res = (from a in lstA
           join b in lstB on a.Prop1 equals b.Prop1
           // Note the "new C" part here, not just "new"
           select new C
           {
               Prop1 = a.Prop1,
               Prop2 = a.Prop2,
               Prop3 = b.Prop3
           }).ToList();
Related Topic