Avoid duplicates in linq based on single column - asp.net

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();

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();
}

Insert records in database in which have 3 foreign keys

I'm trying to insert a record in the table but the problem is in that table have 3 foreign keys. I'll be using dataTable for that but it gives an error 'There is no row position at 0'
                             
There is my code:
try
{
using (var sqlConnection = new Helpers.SqlConnectionHelpers())
{
var connection = sqlConnection.OpenConnection();
command = new SqlCommand("CarSold_Insert", connection);
command.CommandType = CommandType.StoredProcedure;
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = '" + txtPrice.Text + "'", connection);
DataTable table = new DataTable();
DataSet dataSet = new DataSet();
table.Load(commandTwo.ExecuteReader());
var carForSaleId = table.Rows[0]["CarForSaleId"].ToString();
var userId = table.Rows[0]["UserId"].ToString();
var salesPersonId = table.Rows[0]["SalesPersonId"].ToString();
command.Parameters.AddWithValue("CarForSaleId", carForSaleId);
command.Parameters.AddWithValue("UserId", userId);
command.Parameters.AddWithValue("SalesPersonId", salesPersonId);
command.Parameters.AddWithValue("Price", txtPrice.Text);
command.Parameters.AddWithValue("DateSold", dateSold);
command.Parameters.AddWithValue("MonthlyPaymentDate", monthlyPaymentDate);
command.Parameters.AddWithValue("MonthlyPaymentAmount", txtPaymentAmount.Text);
//connection.Open();
int k = command.ExecuteNonQuery();
command.Parameters.Clear();
if (k != 0)
{
Response.Redirect("~/AdminPanel/CarSold.aspx");
}
else
{
lblAns.Text = "Record Not Inserted into the database";
lblAns.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
lblAns.Text = ex.Message;
}
Since Price column is float you need to write query with query parameter like this:
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = #Price", connection);
commandTwo.Parameters.AddWithValue("#Price", txtPrice.Text);
The above mentioned command will give return you the carForSaleId, userId, salesPersonId which you will use in the insert command

Get Distinct data from datatable present in webservices using linq

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);

Fetching Data from database as per details

string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.
Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}

changing label text on selectedindexchanged of dropdown

I need the address (below the dropdown) to change as per the name that is selected in the dropdown... (they are all for one user only)...! (i donno why this keeps saying your post seems only code!!!!!!)
public DataSet BindDropDownListToAUserAddress2()
{
UserFunctions objGetSession = new UserFunctions();
string strSession = objGetSession.GetEmailFromSession();
DataSet dsUserAddress = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "(SELECT FirstName +' '+ LastName as FullName, * FROM AUserAddress inner join AState on AUserAddress.State_ID = AState.ID inner join ACountry on AUserAddress.Country_ID = ACountry.ID inner join AUser on AUserAddress.AUser_ID=AUser.ID where AUser.Email='" + strSession + "')";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(dsUserAddress, "AUserAddress");
con.Close();
return dsUserAddress;
}
protected void ddlName_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dsUserAddress = objBindDDL.BindDropDownListToAUserAddress2();
string strSession = objGetSession.GetEmailFromSession();
ddlName.SelectedValue = "FullName";
if (objBindDDL.BindDropDownListToAUserAddress2() != null && objBindDDL.BindDropDownListToAUserAddress2().Tables.Count > 0)
{
lblDisplayFirstName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["FirstName"].ToString();
lblDisplayLastName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["LastName"].ToString();
lblDisplayAddressLine1.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine1"].ToString();
lblDisplayAddressLine2.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine2"].ToString();
lblDisplayAddressLine3.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine3"].ToString();
lblDisplayCity.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["City"].ToString();
lblDisplayState.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["StateName"].ToString();
lblDisplayCountry.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["CountryName"].ToString();
lblDisplayPostalCode.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["PostalCode"].ToString();
}
}
when you are binding data to dropdown list
ddlStatus.DataTextField = "FullName";
ddlStatus.DataValueField = "Id";
onselected index change event
int ID =Convert.Toint32(ddlName.SelectedValue)
by using this ID select only this ID Record from the dataTable and display

Resources