简体   繁体   English

如何将数据表中的值存储到数组中,并使用C#中的for循环从数组中检索每个值?

[英]how to store values from datatable to array and retrive each values from array using for loop in c#?

 con001.Open();
        SqlCommand cmd001 = new SqlCommand("select distinct TruckRegistration.Id from booking_txn inner join Payments on  booking_txn.booking_ID=Payments.booking_ID inner join truck_log on  booking_txn.booking_ID=truck_log.booking_id inner join TruckRegistration on TruckRegistration.Id=truck_log.truck_id inner join booking_master on booking_master.booking_ID=booking_txn.booking_ID where booking_master.booking_pickupdate between '10-Jul-2016'  and '10-Aug-2016' ", con001);
        DataTable myDataTable = new DataTable();
        SqlDataAdapter ad = new SqlDataAdapter(cmd001);
        con001.Close();
        ad.Fill(myDataTable);


        List<String> trucklist = new List<String>();

        foreach (DataRow dataRow in myDataTable.Rows)
        {

            trucklist.Add(string.Join(";", dataRow.ItemArray.Select(item => item.ToString())));
        }


*I Have stored values from a datatable to trucklist array*

After this what is to be done is, to store every value in array to seperate string using for loop. 此后要做的是,使用for循环将每个值存储在数组中以分隔字符串。

 foreach (String currentTruck in truckList)
  {
    // do something with currentTruck
  }

or 要么

  for (int i = 0; i < truckList.Count; i++)
  {
    String currentTruck = truckList[i];
    // do something with currentTruck
  }

Your example is similar to the code below, which will just fill 2,3,4,5 at different indexes of the stringList . 你举的例子是类似下面的代码,这将只需填写2,3,4,5在不同指标stringList If beside Id one more column is added to the class A , then would have some impact of string.Join 如果在Id旁边再向class A添加一列,则会对string.Join产生一些影响。

void Main()
{
    List<A> intList = new List<A> { new A { Id = 2}, new A { Id = 3}, new A { Id = 4}, new A { Id = 5}};

    List<string> stringList = new List<string>();

    var propertyArray = intList.First().GetType().GetProperties();

    foreach (var x in intList)
    {

        stringList.Add(string.Join(";",propertyArray.Select(y => y.GetValue(x,null))));
    }

  // Print StringList    
}

public class A
{
    public int Id { get; set;}
}

Edit 编辑

  • Convert to Array , use following code: 转换为Array ,使用以下代码:

     var stringArray = stringList.ToArray(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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