views:

123

answers:

4

Hi, I'm having the following issue:

I'm using linq to filtrate some data in this way:

var listPerson = (from objPerson in ListPerson
                                 select new
                                 {
                                     objPerson.IdPerson,
                                     objPerson.ApePerson,
                                     objPerson.NomPerson,
                                     objPerson.EdadPerson,
                                     objPerson.Gender
                                 }).Distinct();

Everything works fine, but the problem is when i tried to cast the listPerson List to a

List<PersonClass>

How can i do that cast ? I tried:

listPerson.ToList();

But it throws an exception (cannot convert from IEnumerable to IEnumerable).

Thanks in advance. I hope i made myself clear.

A: 

You have the collection of instances of the anonymous class that are created with new { ... } syntax. It cannot be converted to a List of instances of PersonClass without converting each item to PersonClass instance.

thorn
+1  A: 

I assume you are using linq on a list of PersonClass objects, so why not just select the object. Using the new keyword creates an anonymous class, which is not a PersonClass.

var DistPerson = (from objPerson in ListPerson 
                  select objPerson).Distinct(); 

var DistPersonList = DistPerson.ToList();
Wade73
+2  A: 

You are creating an anonymous type in your linq statement. You need a way to convert the instances of that anonymous type to instances of the PersonClass.

If ListPerson is an IEnumerable<PersonClass>, you should be able to just do ListPerson.Distinct().ToList().

Franci Penov
+1 for posting the best way to get the data.
Wade73
+1  A: 

var listPerson is of type IEnumerable<COMPILERGENERATEDANONYMOUSTYPE>, not a IEnumerable<PersonClass>.

instead of

select new
{
  objPerson.IdPerson,
  objPerson.ApePerson,
  objPerson.NomPerson,
  objPerson.EdadPerson,
  objPerson.Gender
}

do:

select new PersonClass()
{
  IdPerson = objPerson.IdPerson,
  // etc
}

If you really need that anonymous type there, and to convert it to a list later, then you can do another select:

listPerson.Select(p => new ListPerson() { IdPerson = p.Person, /* ... */ });

or

listPerson.Select(p => new ListPerson(p.Person, /* ... */ ));
Merlyn Morgan-Graham
Thanks a lot! You solved my issue.
lidermin