问题
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.
回答1:
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, /* ... */ ));
回答2:
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()
.
回答3:
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.
回答4:
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();
来源:https://stackoverflow.com/questions/1917188/convert-ienumerable-linq-list-to-typed-list