Comparing data from 2 tables and display the result on a dropdownlist using LINQ - asp.net

I have the 2 following tables: Country and Postal
I retrive all the countries in a DropDownAddCountry and i wan't by doing that to display all the postals belonging to the country in another dropdown (DropDownAddPostals).
The country table have a coulmn CountryID and postal also have a coulm CountryID. So i wan't the result to be based on match between CountryID and CountryID (from both tables):
My code look like this now (and it's not correct):
using (DB_Entities tt = new DB_Entities())
{
var sql = from q1 in tt.Country
join q2 in tt.Postal on q1.CountryID equals q2.CountryID
select new { q2.Postal1 };
if(sql != null)
{
DropDownAddPostal= sql.Postal1;
}
}
Cheers

Don't use anonymous types (especially if they are not necessary).
You can set the collection to your DropDownList with the DataSource-Property.
using (var tt = new DB_Entities())
{
var sql =
from q1 in tt.Country
join q2 in tt.Postal on q1.CountryID equals q2.CountryID
select q2.Postal1
DropDownAddPostal.DataSource = sql.ToList();
DropDownAddPostal.DataBind();
}

Related

c# entity framework lookupedit province district

I want to list the province and district using lookupedit, but it gives an error, please help
var iller = (from x in db.TBL_ILLER
select new
{
x.ID,
x.SEHIR
}).ToList();
LkpIll.Properties.ValueMember = "ID";
LkpIll.Properties.DisplayMember = "SEHIR";
LkpIll.Properties.DataSource = iller;
I have listed the provinces like this, but I cannot list the counties

Count resulted records using linq to sql

i use linq to sql query for retrive records from database.
i use a query,for binding a gridview.
protected void grdBind()
{
try
{
EventManagerDataContext db = new EventManagerDataContext();
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
where y.ClientID==x.EventID
select x.EventID).Count();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events = z,
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
EventID = b.EventID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
catch
{
throw;
}
}
and i recieve this output for that,
i recieve this output for this query but i don't want this output ,
i want like this output.
clientname events
ketan 18
monika 12
and others records so on means i recieve here client name 9 times and he created events but i want some of events and client name only one time
means i want only one name of client and total number of events,i am new to linq to sql.
so what is the changes in code..?
when you are using join syntax in query you do not need to use 'where'
then change your query to :
var z = (from x in db.EMR_EVENTs
join y in db.EMR_CLIENTs on x.ClientID equals y.ClientID
select x.EventID).Count();
i found solution .here
ans also use with this.useful link
here is my solution.
EventManagerDataContext db = new EventManagerDataContext();
var q = from a in db.EMR_CLIENTs
join b in db.EMR_EVENTs on a.ClientID equals b.ClientID into z
join c in db.EMR_ACCOUNTs on a.ClientID equals c.ClientID
join d in db.EMR_SUBSCRIPTIONs on c.Account_ID equals d.Account_ID
join f in db.EMR_SUBSCRIPTION_KINDs on d.Subscription_kind_ID equals f.Subscription_kind_ID
select new
{
Customer = a.Name,
Events =z.Where(b =>b.ClientID==a.ClientID).Count(),
TurnOver = f.Monthly_Fee,
StartDate = d.Start_Date,
EndDate = d.End_Date,
CreteDate = d.Create_Date,
ClientID = a.ClientID,
SubscriptionID = d.Subscription_ID,
Subscription_kind_ID=f.Subscription_kind_ID,
Account_ID=c.Account_ID,
};
grid.DataSource = q.ToList();

How to select greater number and lower number using LINQ To SQL in C#

I have a TABLE in SQL Database there is a columns in
TABLE ID,Subject,Body,Status,TimeDate in the 400 row data and each i have take a Id as a P_Key and Identity Specification is Yes.
Here is Id = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 etc..
I want to select greater Id from table based on saved old id like i have saved ID 12 in im getting same id like this with Linq Query below:
public static int CheckId()
{
DataClassesDataContext con = new DataClassesDataContext(Globals.con);
var q = from v in con.TABLE
where v.Id== 12 & v.Status == Active
select v.Id;
foreach (var val in q)
{
return Convert.ToInt32(val);
}
return 0;
}
the i can return a greater id then 12. and there is also one issue. if there is greater ID is Missing from DB example Id 13 is missing then i will get Id 14 in that case. please let me know how can i get id like this i want from db using linq query.
Use Min
return con.<TABLE>
.Where(v=>v.ID > 12)
.Select(v=>v.ID)
.DefaultIfEmpty()
.Min();
I made a sample for you
List<Int32> test = new List<Int32>{1,2,3,4,5,6,7,8,9,10,11,12,14,13,15,16};
var min = test.Where(x=>x>12).Min();
Gives result 13 only, even when 14 is the first bigger
In Your case
//get a table object
Table table = new Table() //if you want whole row.
table = con.Table.Where(x=>x.id>12).MIN();
Based on the code you already have:
DataClassesDataContext con = new DataClassesDataContext(Globals.con);
var q = from v in con.TABLE
where v.Id > 12 & v.Status == Active
orderby v.Id
select v.Id;
return q.Take(1); // to return the whole row
// or
return q.Take(1).Id; // to return only the Id
This would return the first row meeting the criterias (id > 12, status = active). Add error handling code as needed.

How to create duplicate rows based on some conditions?

My Datatable has some columns that contains data in the format as 2011~|~2012~|~2013. Now the table has only one row. But based on how many such data is there, that many rows should be created
Hence, in the above format, three rows should be created each having Year column filled as 2011, 2012 and 2013. It doesn't matter that if other columns are being duplicated
Format similar to Year column also exists for some 2-3 more columns such as Sales column states figures as 190~|~250~|~488.
One Important Note: The number of rows here should be 3 (considering year & sales column). It should not be 9 (3 x 3). There is a one-to-one relationship, say in year 2011 sales was 190mn$, for 2012 it was 250 mn$ and for 2013 expected is 488mn$.
The below image explains more in detail.
I guess the funda is cleared. If not, let me know.
Please guide
Are you looking for something like this?
private DataTable AlterDataTable(DataTable oldTable)
{
DataTable newTable = oldTable.Clone();
foreach (DataRow row in oldTable.Rows)
{
var years = row["Year"]
.ToString()
.Split(new string[] { "~|~" }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
foreach (var year in years)
{
row["Year"] = year;
newTable.ImportRow(row);
}
}
return newTable;
}
Call it as DataTable dataTable = AlterDataTable(dt);
For this requirement, try this
private DataTable AlterDataTable(DataTable oldTable)
{
DataTable newTable = oldTable.Clone();
foreach (DataRow row in oldTable.Rows)
{
var years = row["Year"]
.ToString()
.Split(new string[] { "~|~" }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var sales = row["Sales"]
.ToString()
.Split(new string[] { "~|~" }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
if (years.Count != sales.Count)
{
throw new Exception("Argument count mismatch exception");
}
for (var i = 0; i < years.Count; i++)
{
row["Year"] = years[i];
row["Sales"] = sales[i];
newTable.ImportRow(row);
}
}
return newTable;
}
Please note that the splits should be having the same count.

how group by in Linq with 2 Field?

how group by in Linq with 2 Field ?
(from i in info
group i by i.OrderId into g
select new { orderId = g.Key, infos = g });
not only order by with order Id but with two field like ...
group by i.orderId And i.City
how this will do?
I believe you want something like this:
var result = from i in info
group i by new { OrderId = i.OrderId, City = i.City } into g
select new { OrderId = g.Key, Infos = g };
Creating the key as an anonymous type simply allows LINQ to use the default equality comparers for all the fields of the anonymous type, which should do the job in most situations.
As a follow-up to Noldorin's answer, you can omit the field names on the anonymous type when they match the fields you're setting them to.
Example:
var result = from i in info
group i by new { i.OrderId, i.City } into g
select new { OrderId = g.Key, Infos = g };
Another follow-up to the Noldorin's and Josh Einstein's answers...OrderID will take on the entire key...which in this case is a new object with two properties, OrderID and City. If your final result set needs the OrderID to be the OrderID, then you'll need to do the following:
var result = from i in info
group i by new { i.OrderId, i.City } into g
select new { OrderId = g.Key.OrderId, Infos = g };

Resources