简体   繁体   中英

How to create an object dynamically from a string array?

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

You only take the first three values to create a Person object and then call AddNewRecord every 3rd iteration. Instead, every 3rd iteration you will need to set p to a new Person in order to prevent mutating the existing Person object already used to invoke AddNewRecord . To avoid only using the 3 first array elements, you want to % 3 on them too. 0 % 3 = 0, 1 % 3 = 1, 2 % 3 = 2, 3 % 3 = 0. Any number % 3 will tell you whether you're on the ID, Name or Age.

I think it's worth asking why you have an array of strings containing object data. Why not create the Person before putting all of their info in an array to avoid this problem?

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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM