Learner
Learner

Reputation: 447

Casting Anonymous type known model

My model class is like this:

Public class abc {

         public string p1 get; set;
         public string p2 get; set;
}

and I am trying to cast like this

IEnumerable<abc> data= ( IEnumerable<abc>) (from d in d.GetAll()
                       select new {
                        p1= d.p1,
                        p2= d.p2
                     }).Distinct();

It is giving me error:

Unable to cast object of type <DistinctIterator>

Please advise

Upvotes: 0

Views: 491

Answers (1)

JamieSee
JamieSee

Reputation: 13010

You cannot directly cast an anonymous type to a known type. Do this instead:

IEnumerable<abc> data = from d in d.GetAll()
                    select new abc() {
                     p1 = d.p1,
                     p2 = d.p2
                  }).Distinct();

and if necessary create an IEqualityComparer to use with your Distinct call. See Enumerable.Distinct Method (IEnumerable, IEqualityComparer) for an example of implementing IEqualityComparer with Distinct.

Upvotes: 3

Related Questions