Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<AnonymousType> to List<string>

I want to convert a List<AnonymousType> to List<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 variable List<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

like image 763
CiccioMiami Avatar asked Apr 19 '11 17:04

CiccioMiami


2 Answers

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>

like image 103
Bala R Avatar answered Sep 28 '22 21:09

Bala R


You cannot assign List<AnonymousType> to List<String>, that types are not compatible.
Use lkpiToDiplay.Select(i => i.ToString()).ToList()

like image 36
STO Avatar answered Sep 28 '22 20:09

STO