Get Distinct data from datatable present in webservices using linq - asp.net

I want to get only single row from multiple rows with same projectname from the datatable.(Eg. if we have two rows with same projectname,the datatable should be loaded with the only one row and neglect the other one.).I have been using webservices which has the datatable.
I want to achieve this functionality using linq.
I have pasted my code for datatable.Pls help me with working code.
[WebMethod]
public DataTable Get()
{
int a = 0;
cmd = con.CreateCommand();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = " Select PROJECTNAME,COMPANY,PROJECTSTATUS,STARTEDIN,COMPLETEDIN FROM CMPPROJECT WHERE STATUS ='" + a + "'";
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "CMPPROJECT";
sda.Fill(dt);
return dt;
}
}
}

You can create a DataView object which has a method ToTable in which you can pass true to parameter distinct to select distinct rows. But this has no sense to me. I would do this directly in a select query:
DataTable d = new DataTable("CMPPROJECT");
d.Columns.Add("PROJECTNAME");
d.Columns.Add("COMPANY");
d.Rows.Add(1, 1);
d.Rows.Add(1, 1);
d.Rows.Add(2, 2);
d = new DataView(d).ToTable("CMPPROJECT", true, "PROJECTNAME", "COMPANY");
Here is `linq solution:
var select = (from a in d.AsEnumerable()
select new { c1 = a["PROJECTNAME"], c2 = a["COMPANY"] }).Distinct().ToList();
d.Clear();
foreach (var item in select)
d.Rows.Add(item.c1, item.c2);

Related

How to store a select query result ( one result ) to a variable using executescalar() ? ( ASP.NET )

i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}

Avoid duplicates in linq based on single column

i have been retrieving data from datatable using linq.i have retrieved the data successully too.the problem is ,i have to show only one record if two records have same projectname (irrespective of which record,but one record must be shown from the dupicate records).
for multiple records with same projectname, only one record from it should be shown.
I have pasted my working code.
cmd.CommandText = " Select PROJECTNAME,COMPANY,PROJECTSTATUS,STARTEDIN,COMPLETEDIN FROM CMPPROJECT WHERE STATUS ='" + a + "'";
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "CMPPROJECT";
sda.Fill(dt);
var select = (from ab in dt.AsEnumerable()
select new { c1 = ab["PROJECTNAME"], c2 = ab["COMPANY"], c3 = ab["PROJECTSTATUS"], c4 = ab["STARTEDIN"], c5 = ab["COMPLETEDIN"] }).Distinct().ToList();
dt.Clear();
foreach (var item in select)
dt.Rows.Add(item.c1, item.c2, item.c3, item.c4, item.c4);
return dt;
}
Please help me with modified working code..
You can use GroupBy:
var projectGroups = dt.AsEnumerable()
.Select(row => new
{
project = row.Field<string>("PROJECTNAME"),
company = row.Field<string>("COMPANY"),
status = row.Field<string>("PROJECTSTATUS"),
startedin = row.Field<DateTime>("STARTEDIN"), // presumes a DateTime-column
completedin = row.Field<DateTime>("COMPLETEDIN") // presumes a DateTime-column
})
.GroupBy(x => x.project)
.Select(g => g.First())
.Distinct()
.ToList();

Count Numbers of Argument in Function

there are three arguments are passing in function,
but i want to dynamically count the numbers of arguments.
public List<ccBillDataObject> GetBill(string BranchID, string FromDate, string ToDate)
{
List<ccBillDataObject> BillList = new List<ccBillDataObject>();
conn = new SqlConnection(ConnectionString);
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spGetBill";
DateTime dteFromDate = Convert.ToDateTime(FromDate);
DateTime dteToDate = Convert.ToDateTime(ToDate);
cmd.Parameters.AddWithValue("#intBranchID", BranchID);
cmd.Parameters.AddWithValue("#dteFromDate", dteFromDate);
cmd.Parameters.AddWithValue("#dteToDate", dteToDate);
sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
dt = new DataTable();
}
I think you should make a class for this Function. But if you really don't want to, you could use dynamics:
public List<ccBillDataObject> GetBill (IEnumerable<dynamic> list)
{
foreach (dynamic item in list)
{
string name = item.Name;
int id = item.Id;
}
}
Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.

how to check in if condition it is string or not

in my search function i need to pass two parameters to SP.Here i kept if condition for that.But am not getting required output. here is my code.any one help me
if (IsValid)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("spRedemItem", con);
cmd.CommandType = CommandType.StoredProcedure;
if(Parameter.Equals(DropDownList2.SelectedValue=="CustomerCode"))
{
cmd.Parameters.AddWithValue("#CustomerCode", txtkey2.Text);
}
else
{
cmd.Parameters.AddWithValue("#CustomerName", txtkey2.Text);
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["CustomerName"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
Label10.Text = dt.Rows[0]["ItemCode"].ToString();
Label11.Text = dt.Rows[0]["CustomerName"].ToString();
Label12.Text = dt.Rows[0]["PointsNeeded"].ToString();
// Session["CustomerName"] = dt;
View.DataBind();
con.Close();
}
If your sproc has two parameters then you need to pass two parameters every time. Generally you would write your SQL code such that you can just pass NULL to any parameters that you want to ignore, e.g. WHERE (#Column1 IS NULL OR Column1 = #Column1). You then use DBNull.Value for the parameter value if you want to ignore that parameter. You can't use AddWithValue though, because a data type can't be inferred.
E.g.
command.CommandText = #"SELECT *
FROM MyTable
WHERE (#C1 IS NULL OR C1 = #C1)
AND (#C2 IS NULL OR C2 = #C2)";
command.Parameters.Add("#C1", SqlDbType.Int).Value = (someValue == "int"
? Convert.ToInt32(myTextBox.Text)
: (object) DBNull.Value);
command.Parameters.Add("#C2", SqlDbType.VarChar, 50).Value = (someValue == "string"
? myTextBox.Text
: (object) DBNull.Value);

Populating a drop down list dynamically in ASP.net, and passing that value to another query?

2 questions for everybody.
1) How can I order the years by their value, it crashes when I use DESC?
2) If I populate my list like so:
string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
How can I make the year selected appear under ddItems.SelectedItem?
WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";
That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.
Regards.
EDIT:
To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?
First, in your sql you are missing "order by"...use this
"Select Distinct Year from MonthlySales order by Year DESC"
Second, you need to make use of the SelectedValue property to get your dropdown's selected value...as below...
WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";
Having said that, I strongly recommend you to use..."parameterized" sql...Here is an example on how you could enable parameterized sql query...
Give me parameterized SQL, or give me death
Update:
Looks like you are binding your dropdown on every post back...you may try this...
if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
Ans 1)
cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"
You are missing order by. Here it is.
"Select Distinct Year from MonthlySales order by Year DESC";
For your second part you can do this. Please mind the space in " GROUP BY Name"
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";
using (DataSet objDs = new DataSet())
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter())
{
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
}
}
}
}

Resources