Snedden27
Snedden27

Reputation: 1920

Having trouble trying to implement a query on dataset/datatable

I have a data set say 'ds' which I populate from a table called tran_dtls , now I want to write a method to this data set(or the table in the data set 'dt'),which would effectively retrieve for me a scalar value having the same output as this query:

 select sum(amt) from TRAN_DTLS 
 where GL_CODE='" + row["gl_code"].ToString() + "' 
 and SUB_CODE='" + row["sub_code"].ToString() + "' 
 and DBCR='C'"

Here amt,GL_code,SUb_code,DBCR are the columns in tran_dtls table, So what I want to do is select the sum of amount having various conditions ,I have never done anything like this before so I don't know even this would be possible or not

Upvotes: 1

Views: 88

Answers (1)

Andomar
Andomar

Reputation: 238048

I don't think you can write SQL against a DataSet. But you can use LINQ:

var ds = new DataSet();
var tranDtls = new DataTable("tran_dtls");
tranDtls.Columns.Add("gl_code", typeof(string));
tranDtls.Columns.Add("amt", typeof(int));
var row = tranDtls.NewRow();
row["gl_code"] = "a";
row["amt"] = 1;
tranDtls.Rows.Add(row);
ds.Tables.Add(tranDtls);

var result = ds.Tables["tran_dtls"].AsEnumerable()
    .Where(r => (string)r["gl_code"] == "a")
    .Select(r => (int)r["amt"])
    .Sum();

Upvotes: 1

Related Questions