从DataTable中的数据行中选择并提取值 - C#

时间:2011-11-16 14:09:28

标签: c# datatable

我有一个接受这些参数的方法:

public bool CalculateProvent(ArrayList UPs, 
                             ArrayList DateExtraction, 
                             DataTable SourceData

{

...
...
}

SourceData数据表具有此内容(例如):

UP - DateExtraction - Energy1 - Energy2 - Consumption1 - Consumption2 - etc

有一些值:

780 - 2011-11-12 14:00:00 - 30.50 - NULL - NULL - 12.00
780 - 2011-11-12 15:00:00 - 31.50 - NULL - 10 - 12.00
781 - 2011-11-12 14:00:00 - NULL - 6 - NULL - 12.00
...

我必须根据UPs和DataExtraction arraylist来迭代这个数据表,以提取所需的字段值(Energy1等)。

例如:

Decimal myEnergy1, myEnergy2, myConsumption1, myConsumption2

foreach(int up in UPs)
{
    foreach(DateTime myTime in DateExtraction)
  {

   // Here I have to select the correct row and extract my fields
  }

}

如何在此迭代中选择正确的值?

2 个答案:

答案 0 :(得分:1)

我认为这样的事情可能就是你想要的。

var q = from up in UPs.Cast<int>()
        from myTime in DateExtraction.Cast<DateTime>()
        join r in SourceData.AsEnumerable() on 
          new { r.Field<int>("UP"), r.Field<DateTime>("DateExtraction")} equals
          new { up, myTime }
        select new
        {
           Energy1 = r.Field<Decimal>("Energy1"),
           Energy2 = r.Field<Decimal>("Energy2")
        };

答案 1 :(得分:0)

试试这个:

foreach(int up in UPs)
{
  foreach(DateTime myTime in DateExtraction)
  {
    DataRow[] myRows = SourceData.Select("UP=" + up + " AND DateExtraction='" + myTime.ToString() + "'");

    if(myRows != null && myRows.Length == 1)
    {
      // here is your row... myRows[0]
    }
  }
}

当然应该改进并注意myTime.ToString()格式。当然,这也可以通过漂亮而紧凑的LINQ to DataSets来完成