如何将值与行添加到控制台应用程序中的现有数据表

时间:2015-10-27 10:54:50

标签: c# console

我有数据表,我必须执行过滤器,例如where,order by。我有customerName列表。我想过滤每个客户名称的数据 我在下面尝试了同样的代码

 foreach (string customer in CustName)
            {
 Datarow[] DataDR = TradeFinanceBF3.Select(TradeFinanceBF3.Columns["Cust_Name"].ColumnName.Trim() + "='A'", "USD equi DESC");
      }     

我得到datarow,然后如何将它传递给dataTable,以及如何将所有客户数据传递给相同的数据表。

我尝试使用LinkQuery来过滤数据,如下所示

      foreach (string customer in CustName)
            { 
 DataTable selectedTable = TradeFinanceBF3.AsEnumerable()
                          .Where(r => r.Field<string>("Cust_Name") == customer)
                          .OrderByDescending(r => r.Field<double>("IndexABC"))
                          .CopyToDataTable();

        ///Datable OutPut= ????? 

       }

我有数据表,但是如何将所有客户数据添加到一个数据表?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

DataRow[] result = TradeFinanceBF3.Select("Cust_Name ='A'", "USD equi DESC");

DataTable aux = TradeFinanceBF3.Clone();

        foreach (DataRow record in result)
        {
            aux.ImportRow(record);                
        }

答案 1 :(得分:0)

我希望它能解决您的问题

    [Test]
    public void GetCustomerData()
    {
        DataTable TradeFinanceBF3 = GetTable();
        DataTable NewDatatable = TradeFinanceBF3.Clone();
        IList<string> CustName = new List<string> { "Janet", "David" };
        var selectedTable = (from dataRow in TradeFinanceBF3.AsEnumerable()
            join customerName in CustName on dataRow.Field<string>("Cust_Name") equals customerName
            select new
            {
                CustName = dataRow["Cust_Name"],
                IndexABC = dataRow["IndexABC"]
            }).OrderByDescending(p=>p.IndexABC);
        foreach (var table in selectedTable)
        {
            NewDatatable.Rows.Add(table.CustName, table.IndexABC);
        }
        Console.Write(NewDatatable);
    }

    private DataTable GetTable()
    {
        // Here we create a DataTable with four columns.
        DataTable table = new DataTable();
        table.Columns.Add("Cust_Name", typeof(string));
        table.Columns.Add("IndexABC", typeof(double));
        // Here we add five DataRows.
        table.Rows.Add("David", 1);
        table.Rows.Add("Sam", 2);
        table.Rows.Add("Christoff",2);
        table.Rows.Add("Janet", 4);
        table.Rows.Add("Melanie", 6);
        return table;
    }