-1

I have two string say cityIds and cityNames.

cityIds="1,2,3"
cityNames="Pune,Mumbai,Surat"

I have one class say City.cs

public class City
{
    public int CityId { get; set; }
    public string CityName { get; set; }
}

From cityIds and cityNames I want to create List.

So if I have Input like this

cityIds="1,2,3"
cityNames="Pune,Mumbai,Surat"

I want output like this

list[0]=CityId=1,CityName="Pune"
list[1]=CityId=2,CityName="Mumbai"
list[2]=CityId=3,CityName="Surat"

I tried this

var listOfIds = cityIds.Split(',');
var listOfNames = cityNames.Split(',');
for(int i = 0; i < listOfIds.Count; i++)
{
     listOfDealerCities.Add(new City()
     {
          CityId = Int32.Parse(listOfIds[i]),
          CityName = listOfNames[i]
     });
}

Is there any better way to do this like using LINQ?

Steffi Keran Rani J
  • 3,667
  • 4
  • 34
  • 56
yajiv
  • 2,901
  • 2
  • 15
  • 25

2 Answers2

1
List<City> listOfDealerCities = listOfIds.Select<string, City>(
(t, i) => new City()
{
    CityId = Int32.Parse(t),
    CityName = listOfNames[i]
})
.ToList();
Backs
  • 24,430
  • 5
  • 58
  • 85
1

You could use Linq's Zip method for this:

listOfDealerCities.AddRange(listOfIds.Zip(
listOfNames, (id, name) => new City() 
{
    CityId = int.Parse(id), CityName = name 
}));
bhagat
  • 153
  • 1
  • 11
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86