My data source has 3 columns CYear (Date Type),Country (100 Countries), and Ceremony. I want to compare the data for two countries (Pakistan & India) based on Ceremony in years 2010-2013
My Query
var que = (from e in dataset
where (e.country == "Pakistan" || e.Country == "India"
||e.CYear == 2010 || e.CYear == 2011 || e.Start.Year == 2012)
select e.Ceremony
// Group by for a total number of ceremonies each year
// in the specific countries
// to show to the user for better understanding
How can I compare the data for two countries and get the ceremony details i.e. total number of ceremony in these countries for the mentioned year.
I want to show the data in the table for a better understading of the data.
var que = (from e in dataset
where (e.country == "Pakistan" || e.Country == "India" )
&& (e.CYear == 2010 || e.CYear == 2011 || e.Start.Year == 2012)
select e.Ceremony `enter code here`
First fix the where clause, then group by country and year:
var que = (from e in dataset
where (
(e.country == "Pakistan" || e.Country == "India" ) &&
(e.CYear == 2010 || e.CYear == 2011 || e.Start.Year == 2012)
)
group e by new {e.Country, e.CYear}
).Select(g => new {g.Key.Country, g.Key.Year, Count = g.Count()});
Related
I'm a beginner in Linq queries and I'm wondering if my query can be improved one way ore another:
long vehid = json.VehicleId.Value;
DateTime date = DateTime.Parse(json.date.Value);
var Alerts = (from t2 in entities.Alerts.AsNoTracking()
where
t2.GeneratedTimeLocal.Year == date.Year
&& t2.GeneratedTimeLocal.Month == date.Month
&& t2.GeneratedTimeLocal.Day == date.Day
&& (t2.AlertType == 2 || t2.AlertType == 3)
&& t2.vId == vid
select new
{
GeneratedTimeLocal = t2.GeneratedTimeLocal,
OptionalText = t2.OptionalText
});
return Alerts;
The problem is that the Alerts datatable has a huge amount of data in it that increases day by day and right now it's kind of slow.
The GeneratedTimeLocal field from Alerts datatable is type datetimeoffset(7).
Is there a way to improve this query?
Define a date range to improve the query. Then check the query execution plan and based on that decide if you need a new index or change existing indexes.
long vehid = json.VehicleId.Value;
DateTime dateFrom = DateTime.Parse(json.date.Value).Date; // date with no time
DateTime dateTo = dateFrom.AddDays(1); // add one day to create the date range
var Alerts = (from t2 in entities.Alerts.AsNoTracking()
where
t2.GeneratedTimeLocal >= dateFrom
&& t2.GeneratedTimeLocal <= dateTo
&& (t2.AlertType == 2 || t2.AlertType == 3)
&& t2.vId == vid
select new
{
GeneratedTimeLocal = t2.GeneratedTimeLocal,
OptionalText = t2.OptionalText
});
return Alerts;
On the other hand, remember that this query won't be executed until you do a ToList(), for example.
Try this index:
CREATE INDEX IX_Alert_GeneratedTimeLocal_vId_AlertType_with_include ON Alert(GeneratedTimeLocal, vId, AlertType) INCLUDE(OptionalText)
I'm assuming you're using SQL Server. You could also try a filtered index if the table is huge. Check out this link: https://learn.microsoft.com/en-us/sql/relational-databases/indexes/create-filtered-indexes
I have a Datatable which I'm querying for values:
res = (from rows in dtInvoicesStamped.AsEnumerable()
where rows.Field<string>("Centre Name") == col.Name &&
(rows.Field<string>("Doc Type") == row.Name
select rows).CopyToDataTable();
It works OK until I need to query it for the values of a specific month:
res = (from rows in dtInvoicesStamped.AsEnumerable()
where rows.Field<string>("Centre Name") == col.Name &&
(rows.Field<string>("Doc Type") == row.Name
&& rows.Field<DateTime>("Date Loaded") == period.Month)
select rows).CopyToDataTable();
**Difference is in the 4 row of the above code
If I try to add the period, which is month, it returns me the error
Operator '==' cannot be applied to operands of type DateTime and Int.
If I use only period, it will do ok, but obviously it won't return the data for the whole Month.
What am I missing here? What I need to do in order to add this additional condition to my datatable query?
Try (rows.Field<DateTime>("Date Loaded")).Month == period.Month instead
You cannot directly compare the datetime with month. Use rows.Field<DateTime>("Date Loaded").Month to compare with the month.
res = (from rows in dtInvoicesStamped.AsEnumerable()
where rows.Field<string>("Centre Name") == col.Name &&
(rows.Field<string>("Doc Type") == row.Name
&& rows.Field<DateTime>("Date Loaded").Month == period.Month)
select rows).CopyToDataTable();
I have the following SQL Server query and I need to have it in LINQ, Simple query but I tried several time but I can not get it working.
Here is the SQL query
select *
from td_Accountline
where
BonusPlanID = 1
and Amount > 0
and Ord_Sub_ID like '%SMPORD%'
and MONTH(Created) = 11
and YEAR(Created) = 2013
and Ord_Sub_ID not in (
select Ord_Sub_ID
from td_Accountline
where
BonusPlanID =3 and
Ord_Sub_ID like '%SMPORD%'
)
I have tried with this query but still i am confused
var account=from acc in currentDB.td_Accountline
where acc.BonusPlan.BonusPlanID == 1 && acc.Amount > 0 && acc.Ord_Sub_ID.Contains("SMPORD") && acc.Created.ToDateTime().Month == 11 && acc.Created.ToDateTime().Year == 2013
let accNot = from accN in currentDatabase.td_Accountline
where accN.BonusPlan.BonusPlanID == 3 && accN.Ord_Sub_ID.Contains("SMPORD")
select accN.Ord_Sub_ID
where !accNot.Contains("SMPORD")
select acc;
I want one query please not separate query to reduce database calling.
I think you're almost there. Instead of:
where !accNot.Contains("SMPORD")
It should be:
where !accNot.Contains(acc.Ord_Sub_ID)
Your final Linq query would be:
var account = from acc in currentDB.td_Accountline
where
acc.BonusPlan.BonusPlanID == 1
&& acc.Amount > 0
&& acc.Ord_Sub_ID.Contains("SMPORD")
&& acc.Created.Month == 11
&& acc.Created.Year == 2013
let accNot = from accN in currentDatabase.td_Accountline
where
accN.BonusPlan.BonusPlanID == 3
&& accN.Ord_Sub_ID.Contains("SMPORD")
select accN.Ord_Sub_ID
where !accNot.Contains(acc.Ord_Sub_ID)
select acc;
Regular Expressions won't work in Linq for Entity Framework but you can convert to collection in an in-memory list for you to use Regex.
Something like this:
(from x in td_Accountline where Created.Month = 11 && Created.Year = 2013 select a).ToList().Where(v => Regex.IsMatch(v.Ord_Sub_ID,#"(SMPORD)"))
That way, the match will happen in memory
Try This :
var Ord_Sub_IDs = from n in td_Accountline where n.BonusPlanID == 3 && n.Ord_Sub_ID.Contains("SMPORD") select n.Ord_Sub_ID ;
var result=from n in td_Accountline where n.BonusPlanId == 1 && n.Amount > 0 && n.Ord_Sub_ID.Contains("SMPORD") && n.Created.ToDateTime().Month == 11 && n.Created.ToDateTime().Year == 2013 && Ord_Sub_IDs.Contains(td.Ord_Sub_ID) select n;
I kind of feel guilty asking this question because asked a smiliar one before but I did not get a clear answer. I am building a silverlight program and I need to create a Linq query in the domain service (using wcf ria). I need to calculate the sum here is my code
int lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select c).Sum();
MessageBox.Show(lola.ToString());
Between the parenthesis at Sum() I get an error that says
Error 1 Instance argument: cannot convert from 'System.ServiceModel.DomainServices.Client.EntityQuery' to 'System.Collections.Generic.IEnumerable'
What am I missing?? I know it is syntax problem because I am new to Linq. Please Thank you!
What are you adding up for Sum()? Can you try:
int lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select c.PROPERTYTHATYOUWANTTOADDUP).Sum();
Or perhaps you wanted to count how many items match your query?
int lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select c).Count();
EDIT:
So since you want to add up the AMOUNT property:
decimal lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select (decimal)c.AMOUNT).Sum();
You can also make sure that c.AMOUNT is never null so you don't run into an error in the future:
decimal lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13) && (c.AMOUNT != null))
select (decimal)c.AMOUNT).Sum();
I'm using linq-to-sql for a query like this:
public static List<MyModel> GetData(int TheUserID, DateTime TheDate)
using (MyDataContext TheDC = new MyDataContext())
{
var TheOutput = from a in TheDC.MyTable
where a.UserID == TheUserID
(where a.Date1.Month == TheDate.Month && where a.Date1.Year == TheDate.Year)
OR
(where a.Date2.Month == TheDate.Month && where a.Date2.Year == TheDate.Year)
group a by a.Date1.Date AND by a.Date2.Date into daygroups
select new MyModel{...};
How do I write this to make the OR and the AND statement work? I've tried putting a || and a && in place but it doesn't work and I'm stuck on this query.
Basically, it should return a list of days within a month and in the MyModel, I do counts. For instance, in a column I count the number of appointments set on a given day and in another column I count the number of appointments attended on the same day. Date1 refers to the date the appointments are set and Date2 refers to the dates the appointments are attended. So for example, on March 3rd 2011, I've set 4 appointments (Date1 is 3/11/2011 for these) and they're set for various dates in the future (Date2). During the same date (March 3rd is Date2 this time), I've also attended several other appointments that were set on other dates in the past.
Thanks for any suggestions.
using (MyDataContext TheDC = new MylDataContext())
{
var TheOutput = from a in TheDC.MyTable
where a.UserID == TheUserID &&
(a.Date1.Month == TheDate.Month && a.Date1.Year == TheDate.Year)
||
( a.Date2.Month == TheDate.Month && a.Date2.Year == TheDate.Year)
group a by a.Date1.Date AND by a.Date2.Date into daygroups
select new MyModel{...};
Try removing the 4 extra "where" and change the OR to ||.