How to convert List<AnonymousType> to List<string>
17,027
Solution 1
You can skip the Anonymous Class if you can and if you have no need for it
lkpiTodisplay.Add("Business Target");
or
you can do
lkpiTodisplay.Select( x => x.KPI_Name).ToList();
to get List<String>
Solution 2
You cannot assign List<AnonymousType> to List<String>, that types are not compatible.
Use lkpiToDiplay.Select(i => i.ToString()).ToList()
Author by
CiccioMiami
Updated on June 04, 2022Comments
-
CiccioMiami about 2 years
I want to convert a
List<AnonymousType>
toList<string>
. I have the following code:var lkpiTodisplay = _MGMTDashboardDB.KPIs.Where(m => m.Compulsory == true && m.Active == true) .Select(m => new { KPI_Name = m.Absolute == true ? m.KPI_Name : (m.KPI_Name + "%") }).ToList(); for(int i=1; i<= BusinessTargetCol; i++) { lkpiTodisplay.Add(new { KPI_Name = "Business Target" }); }
This code creates a
List<AnonymousType>
. Then I would like to assign this List to a variableList<string>
, as shown in the following code:DashboardViewModel lYTMDashboard = new DashboardViewModel() { KPIList = (List<string>) lkpiTodisplay, //other assignments };
The casting does not work. How can I convert the variable? Other solutions that modify the first code snippet are welcome, as long as the KPIList variable is kept as a
List<string>
.Thanks
Francesco
-
CiccioMiami about 13 yearsthe second solution is what I was looking for. It was so simple I didn't even think about it! Many thanks