I have two list. from one i want two select few data and then save that data to another list.
var ikj = Model.EmployeeInformationList
.Select(m => new { m.GEmployeeGenInfoID, m.strDesignationName, m.strEmpOldCardNo, m.StrEmpID, m.GFactoryID, m.StrEmpName })
.Distinct().ToList();
List<HolidayAlwEmployeeInfo> targetList = new List<HolidayAlwEmployeeInfo>(ikj.Cast<HolidayAlwEmployeeInfo>());
Model.HolidayAlwEmployeeInfoList = targetList;
but I'm getting this error
Unable to cast object of type '<>f__AnonymousType5`6[System.Guid,System.String,System.String,System.String,System.Guid,System.String]' to type 'FactoryProduct.Entities.Payroll.HolidayAlwEmployeeInfo'
You are trying to cast instance of anonymous type that you created by calling new { m.GEmployeeGenInfoID, m.strDesignationName, m.strEmpOldCardNo, m.StrEmpID, m.GFactoryID, m.StrEmpName } to the type HolidayAlwEmployeeInfo, you can't do that.
Rather, you need to rewrite the first line like this:
var ikj = Model.EmployeeInformationList
.Select(m => new HolidayAlwEmployeeInfo(
m.GEmployeeGenInfoID,
m.strDesignationName,
m.strEmpOldCardNo,
m.StrEmpID,
m.GFactoryID,
m.StrEmpName ))
.Distinct()
.ToList();
and make sure that HolidayAlwEmployeeInfo class has appropriate constructor to take all of the parameters m.GEmployeeGenInfoID, m.strDesignationName, m.strEmpOldCardNo, m.StrEmpID, m.GFactoryID, m.StrEmpName
Alternatively (as Stephen Muecke mentioned in his comment), you can instantiate HolidayAlwEmployeeInfo with a simple constructor and assign properties/fields in the initializer, like this:
var ikj = Model.EmployeeInformationList
.Select(m => new HolidayAlwEmployeeInfo()
{
GEmployeeGenInfoID=m.GEmployeeGenInfoID,
strDesignationName=m.strDesignationName,
strEmpOldCardNo=m.strEmpOldCardNo,
StrEmpID=m.StrEmpID,
GFactoryID=m.GFactoryID,
StrEmpName=m.StrEmpName
})
.Distinct()
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With