Answered by:
Assigning List to IEnumerable model

Question
-
User271039688 posted
Hi,
I need to store the results of the following query into a model type of IEnumerable (model.Applicants) but this generates a type convert error because the applicants object is a list.
Is there any way of converting the list to an IEnumerable or any other way of achieving this please? The model displays the results in a webgrid and so needs to be an IEnumerable.
var applicants = (from c in context.tblapplicants join e in context.tblapplicant_notes on c.ApplicantCode equals e.ApplicantCode orderby e.NoteDate descending select new { c.ApplicantCode, c.Forename, c.Surname }).ToList();
model.Applicants = applicants;Thursday, July 11, 2019 3:46 PM
Answers
-
User753101303 posted
Hi,
Try with:
select c).ToList();and you should get applicants rather than an anonymous type (even if a type has a same properties it is still not the same type).
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, July 11, 2019 5:02 PM
All replies
-
User475983607 posted
Always post the actual error! A List<T> is a type of IEnumerable<T>. The problem with your code is you are returning an anonymous type not an List<Applicant>.
The following projection query is just a guess as you have not posted enough source code to provide an accurate solution. Keep in mind, you can return ToEnumerable() rather than ToList() if needed.
var applicants = (from c in context.tblapplicants join e in context.tblapplicant_notes on c.ApplicantCode equals e.ApplicantCode orderby e.NoteDate descending select new Applicant() { ApplicantCode = c.ApplicantCode, Forename = c.Forename, Surname = c.Surname }).ToList();
Study the LINQ to SQL docs for guidance on writing queries.
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/querying-the-database
Thursday, July 11, 2019 4:43 PM -
User753101303 posted
Hi,
Try with:
select c).ToList();and you should get applicants rather than an anonymous type (even if a type has a same properties it is still not the same type).
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, July 11, 2019 5:02 PM -
User271039688 posted
Thank you so much :-)
Friday, July 12, 2019 8:21 AM