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

时间:2016-09-23 05:03:11

标签: c# arrays

 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*
  

在此之后要做的是,将数组中的每个值存储为使用for循环分离字符串。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您的示例与下面的代码类似,只会在2,3,4,5的不同索引处填充stringList。如果在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;}
}

修改

  • 转换为Array,请使用以下代码:

    var stringArray = stringList.ToArray();