I have a String array in C# like below:
String[] myArray = {"1","Jack","18","2","John","22","3","Mark","29"}
Actually there are 3 objects in my array, first column is ID, second is Name and third is Age. So I need to insert 3 rows into my SQL table, each represents one person.
What is the best way to handle it?
I try:
Person p = new Person();
for (int i = 0; i <= myArray.Length; i )
{
if (i==0) p.Id = myArray[i];
if (i==1) p.Name = myArray[i];
if (i==2) p.Age = myArray[i];
if (i%3==0) AddNewRecord(p);
}
But then how can I remove the first object from my array and start from 0 again?
Thanks.
PS. Couldn't find a proper title for my issue, sorry, appreciate if you may edit.
Edit: Java or C# answer, both fine by me
CodePudding user response:
With your constraints, the best option would probably be to increment by 3.
Here's roughly what that would look like:
for (int i = 0; i < myArray.Length; i =3)
{
AddNewRecord(new Person {
ID = int.Parse(myArray[i]),
Name = myArray[i 1],
Age = int.Parse(myArray[i 2])
});
}
CodePudding user response:
try below code this is worked you expected
for (int i = 0; i <= myArray.Length; i )
{
if (i == 0) p.ID = myArray[i];
if (i == 1) p.Name = myArray[i];
if (i == 2) p.Age = myArray[i];
if (i!=0 && i % 2 == 0)
{
if (myArray.Length > 0)
{
myArray = myArray.Skip(3).ToArray();
}
i = 0;
}
}