Convert list <a> to list <b> using Linq C #
How can I convert my list with the type "Face" (created by my database) to typ "myPerson" without receiving erros.
I tried this:
DataClasses1DataContext d = new
DataClasses1DataContext(MainWindow.mySqlClass.GetConnection());
var query = from pers in d.Person select pers;
personen = query.ToList();
newPerson = personen.Cast<myPerson>().ToList();
But I only get System.InvalidCastException
.
public partial class myPerson : Person
{
public override string ToString()
{
return Name + " " + Nachname;
}
public myPerson(System.Data.Linq.EntitySet<Bilder> bilder, string geschlecht, int iD, string nachname, string name)
{
Bilder = bilder;
Geschlecht = geschlecht;
ID = iD;
Nachname = nachname;
Name = name;
}
}
Class created by Linq (frist strings only):
public partial class Person : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ID;
private string _Nachname;
private string _Name;
private string _Geschlecht;
private EntitySet<Bilder> _Bilder;
Does anyone have an idea how I can convert a List from typ Person to a list with typ myPerson?
or how can I make a request that makes it possible to convert from Person to myPerson?
+4
4 answers
myPerson
Person
, myPerson
Person
. , Person
myPerson
, . , myPerson
, , .
Person
, myPerson
, ( factory), Person
( ) myPerson
.
public partial class myPerson : Person
{
public myPerson(Person p)
{
_ID = p.Id;
_Nachname = p.Nachname;
_Name = p.Name;
_Geschlecht = p.Geschlecht;
_Bilder = p.Bilder;
}
private int _ID;
private string _Nachname;
private string _Name;
private string _Geschlecht;
private EntitySet<Bilder> _Bilder;
// add properties
}
:
personen = query.ToList();
newPerson = personen.Select(p => new myPerson(p)).ToList();
+2
, this StackOverflow ?
Botz3000: "
ChildClassList = BaseClassList.Cast<ChildClass>().ToList();
null
, BaseClass ChildClass. , :
ChildClassList = BaseClassList.Select(x => x as ChildClass).ToList();
But I would prefer this, including type checking, and skip elements that don't match:
ChildClassList = BaseClassList.OfType<ChildClass>().ToList();
"
0