pKumar
pKumar

Reputation: 25

How to query a datatable

I am using a XML file and the data from the XML is set into a dataset and user selected table is stored as a datatable.A query is been generated with filter criteria, grouping, aggregate function, expressions etc.Is it possible to query the datatable? I did come accross table.Select(filter criteria, sort) method.but kindly let me know how grouping, aggregate function and expression (eg: Column1 + Column2 as SumColumn) can be got.

Upvotes: 2

Views: 731

Answers (2)

user153923
user153923

Reputation:

Unfortunately, table.Select(filterCriteria, sort) is your only option without LINQ (I'm not a LINQ guru, so don't ask me what it can do).

Anytime I need something specific, I create/add that column to the DataTable.

        DataTable table = new DataTable();
        // code that populates the table
        DataColumn c = table.Columns.Add("Column1 + Column2", typeof(int));
        int Sum = 0;
        for (int i = 0; i < table.Rows.Count; i++) {
          r = table.Rows[i];
          int col1 = (int)r["Column1"];
          int col2 = (int)r["Column2"];
          int both = col1 + col2;
          Sum += both;
          r[c] = string.Format("{0}", both);
        }
        DataRow summaryRow = table.NewRow();
        summaryRow[c] = (int)((float)Sum / table.Rows.Count + 0.5); // add 0.5 to round
        table.Rows.Add(summaryRow);

HTH.

Upvotes: 1

dugas
dugas

Reputation: 12443

You could query the data using LINQ - assuming you are using a .Net Framework version that supports it. Check out LINQ To Dataset

Upvotes: 2

Related Questions