Hi Could any one help how to write this below query in Linq C#
select YearValue from [Information].Year
where YearId in (select max(YearId) from curreny where BudgetCodeId = 2)
Here's what I've tried:
var maxYear =
from year in dbContext.Years
join exchange in dbContext.CurrencyExchangeRates
on year.YearId equals exchange.YearId
where exchange.BudgetCodeId == budgetCodeId
orderby year.YearValue descending
select new { yearValue = year.YearValue };
This is what you're looking for:
var maxYear = from year in dbContext.Years where (from exchange in dbContext.CurrencyExchangeRates where exchange.BudgetCodeId == 2 select exchange)
.Max(m => m.YearId) ==
year.YearId select year.YearValue;
int mYear = maxYear.First();
Related
I have the following SQL query which has a sub query so that only the max value is in the result set:
Select
t.ID,
r.ResultIdentifier,
p.ProductID,
r.Status,
r.Start
from Result r , Transact t, Product p
WHERE r.ResultIdentifier = (Select MAX(r2.ResultIdentifier) from Result r2
where r2.Status = 'Fail'
and r2.ID = r.ID
and r2.Start >= getdate() - 30)
and r.ID = t.ID
and p.productID = 9
and t.productID = p.productID
I'm trying to convert this to a LINQ query
var failures = from result in db.Results
join transact in db.Transacts on result.ID equals transact.ID
join product in db.Products on transact.ProductID equals product.ProductID
where result.ResultIdentifier == ??
.....
select new{ ID = transact.ID,
...etc
I'm really struggling with the max ResultIdentifier in the LINQ - tried multiple variations with .MAX() but cant seem to get it right.Any suggestions welcome.
You can use the max keyword, Sorry for using method syntax as I can see you are using query :(
Should look something like the following
where result.ResultIdentifier == (Results.Max().Where(x => x.Status.equals("Fail") && x.id == result.id && x.start => Datetime.Now().Add(-30)).Select(x => x.ResultIdentifier))
Try the following query:
var results = db.Results;
var failedResults = results
.Where(r => r.Status == "Fail" && r.Start >= DataTime.Date.AddDays(-30));
var failures =
from result in results
join transact in db.Transacts on result.ID equals transact.ID
join product in db.Products on transact.ProductID equals product.ProductID
from failed in failedResults
.Where(failed => failed.ID == result.ID)
.OrderByDescending(failed => failed.ResultIdentifier)
.Take(1)
where result.ResultIdentifier == failed.ResultIdentifier
.....
select new{ ID = transact.ID,
...etc
I am trying to write a LINQ query that will get me some distinct values from two SQL Server data tables.
I have two tables named, Facility_Cost_TBL and Tenant_Bills_TBL.
I then have a column that is named Nursing_Home_Name which I am trying to get the distinct data from.
This is my effort in LINQ , however it does not work,
var name = (from f in dataContext.Facility_Cost_TBLs
join t in dataContext.Tenant_Bills_TBLs on f.Tenant_Code equals t.Tenant_Code
where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();
And this is a working SQL statement I made that does what I want via T-SQL.
SELECT DISTINCT Nursing_Home_Name
FROM (SELECT Nursing_Home_Name
FROM Facility_Cost_TBL
WHERE Date_Year = 2016 AND Date_Month = 10 AND Tenant_Code = 664250
UNION SELECT Nursing_Home_Name
FROM Tenant_Bills_TBL
WHERE Year_Data = 2016 AND Month_Data = 10 AND Tenant_Code = 664250)
a
Could someone show me what LINQ sytax AND what LINQ extension method query would look like?
Please try following
var names = ((from f in dataContext.Facility_Cost_TBLs
where f.Tenant_Code == "664250" && f.Date_Month == "10" && f.Date_Year == "2016"
select new { Nursing_Home_Name = f.Nursing_Home_Name }).
Union(
from t in dataContext.Tenant_Bills_TBLs
where t.Tenant_Code == "664250" && t.Date_Month == "10" && t.Date_Year == "2016"
select new { Nursing_Home_Name = t.Nursing_Home_Name })).ToList();
Hope this will help you
Try this to see if this works. LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?
var name = (from f in dataContext.Facility_Cost_TBLs
join t in dataContext.Tenant_Bills_TBLs equals on new { f.Tenant_Code, f.Date_Month, f.Date_Year } equals new { t.Tenant_Code, t.Date_Month, t.Date_Year }
where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();
This question already has answers here:
Create a Tuple in a Linq Select
(6 answers)
Closed 6 years ago.
I have 2 database tables.
In Table1 Calculate I have 1 row which is mapped via an Id to multiple rows in table2 CalculdateData.
Now I need to load the data from table1 Calculate with all relevant Details from Table2 CalculdateData.
How would i have the Details into a Tuple-List.?
So basically for CalculateData I have 4 columns per row which I Need to put into a Tuple. Meaning if I would have for example 4 rows i need to create 4 Tuples in a List.
IEnumerable<Storage> context = new MyEntities();
var Result = (from a in context.calculate
join b in context.CalculateData on a.Id equals b.CalcId into c
where a.SpecialID == 2023 && a.VersionId == 1
orderby a.InternalOrderNr ascending
select new Storage
{
myField1 = a.Field1;
myField2 = a.Field2;
myField3 = a.Field3;
< MISSING PART AND QUESTION >
}).ToList();
return Result;
public class Storage
{
public int myField1;
public int myField2;
public int myField3;
public List<Tuple<int, int, string, decimal>> myField4;
}
This should work:
var Result = (from a in calculate
join b in calculateData on a.Id equals b.CalcId into c
where a.SpecialID == 2023 && a.VersionId == 1
orderby a.InternalOrderNr ascending
select new Storage
{
myField1 = a.Field1,
myField2 = a.Field2,
myField3 = a.Field3,
myField4 = c.Select(d => new Tuple<int, int, string, decimal>
(d.Field1, d.Field2, d.Field3, d.Field4))
.ToList()
}).ToList();
return Result;
It also would be good thing to check that this query transforms in single sql request and you not making new sql request on each tuple list creation.
Edit: In case you will have problems with custom types in query (as #Toxantron pointed) this selection should work:
var queryResult = (from a in calculate
join b in calculateData on a.Id equals b.CalcId into c
where a.SpecialID == 2023 && a.VersionId == 1
orderby a.InternalOrderNr ascending
select new
{
a.Field1,
a.Field2,
a.Field3,
myField4 = c.Select(d => new {
d.Field1, d.Field2, d.Field3, d.Field4})
}).ToList();
result = queryResult.Select(r => new Storage
{
myField1 = r.Field1,
myField2 = r.Field2,
myField3 = r.Field3,
myField4 = r.myField4.Select(t => new Tuple<int,int,decimal,string>
(t.Field1, t.Field2, t.Field3, t.Field4))
.ToList()
})
return Result;
You could try something like this.This is not tested yet.
select new Storage
{
myField1 = a.Field1,
myField2 = a.Field2,
myField3 = a.Field3,
myField4 = c.Select(d => new Tuple<int, int, string, decimal>(d.Field1, d.Field2, d.Field3, d.Field4)).ToList()
}).ToList();
This is totally based on this This tutorial
What is the best way to write this query in linq?
SELECT *
FROM product_master
where product_id in (select product_id from product where buyer_user_id=12)
var _result = from a in product_master
where (product.Where(s => s.buyer_user_id == 12))
.Contains(a.product_ID)
select a;
or
var _result = (from a in product_master
join b in product
on a.product_id equals b.product_id
where b.buyer_user_id == 12
select a).Distinct();
JW's answer is correct. Alternatively, given that the subquery is not correlated, you could express it separately:
var pids = product.Where(p => p.buyer_user_id == 12);
var r = product_master.Where(pm => pids.Contains(pm.product_id));
I have a table that has several columns: HarvestID, HarvestDate, UserID to mention the main ones.
For each date, there are going to be several HarvestID per day.
So far, I have the following linq query:
TheUserID and TheMonth are passed in as an int and a DateTime
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
where h.HarvestDate.Month == TheMonth.Month
where h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into TheDays
from d in TheDays
select new
{
TheDay = d.HarvestDate.Date,
TheDayCount = (from c in TheDay
select c.HarvestID).Count()
};
I'm looking to have the output be a list of counts per day. The query doesn't bug but the problem is that at the moment the query is not returning a unique row for each day. The grouping doesn't work and I'm not finding out why. What's wrong with this code?
Thanks.
It think your query should be
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
where h.HarvestDate.Month == TheMonth.Month
where h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into TheDays
select new
{
TheDay = TheDays.Key,
TheDayCount = TheDays.Count()
};
Here is a vry good refrence to above group by statement http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#simple1
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
&& h.HarvestDate.Month == TheMonth.Month
&& h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into g
select new
{
TheDay = g.Key,
TheDayCount = g.Count()
};
This will not give you zeroes on the days where there is no data - but should give you a count where there is.
http://msdn.microsoft.com/en-us/vcsharp/aa336746 is my go-to page for LINQ examples.