I want to convert this to Linq:
SELECT {fields}
FROM tableA AS A
LEFT JOIN tableB AS B
ON B.Field1 = MyVariable
AND ( A.Key = B.Key
OR A.Key = B.AlternateKey)
It's that OR in conjunction with the AND clause that is tripping me over.
EDIT: Can I have the solution as extension methods please.
from a in tableA
from b in tableB.Where(b => b.Field1 == MyVariable && (a.Key == b.Key || a.Key == b.AlternateKey)).DefaultIfEmpty()
select new { a, b };
tableA.SelectMany(
a => tableB.Where(b => b.Field1 == MyVariable && (a.Key == b.Key || a.Key == b.AlternateKey)).DefaultIfEmpty()
.Select(b => new { a, b })
);
Related
I have this sql query that needs to be in linq. I'm really new to it so I still cant figure out how to use it.
SELECT a.Fecha, a.ContratoId, a.TotalContrato, a.Plazo, a.ValorCuota, a.Fecha_de_vencimiento
FROM Contrato AS a LEFT JOIN Contrato_detalle AS b ON a.ContratoId = b.ContratoId
AND a.ContratoId < b.ContratoId
Left join Contrato_plan_pagos c on a.ContratoId = c.ContratoId
And a.ContratoId < b.ContratoId
Please try this:
var resultsQueryable = from a in Contrato
join b in Contrato_detalle on a.ContratoId equals b.ContratoId into abGroup
from ab in abGroup where a.ContratoId < ab.ContratoId
join c in Contrato_plan_pagos on a.ContratoId equals c.ContratoId into acGroup
from ac in acGroup where ContratoId < c.ContratoId
select new {
a.Fecha,
a.ContratoId,
a.TotalContrato,
a.Plazo,
a.ValorCuota,
a.Fecha_de_vencimiento
};
var results = resultsQueryable.ToList();
or
var resultsQueryable = Contrato.GroupJoin(Contrato_detalle,
a => a.ContratoId, b => b.ContratoId, (a, comp) => new {v = a, comp})
.SelectMany(x => x.comp, (t1, b) => new { a = t1.v, b = b })
.Where(abGroup => abGroup.a.id < abGroup.b.id)
.GroupJoin(Contrato_plan_pagos, t => t.b.ContratoId, c => c.ContratoId, (t, grp) => new {t, grp})
.SelectMany(t => t.grp, (t, c) => new {a = t.t.a, b = t.t.b, c = c})
.Where(acGroup => acGroup.a.id < acGroup.c.id)
.Select(x => new {
a.Fecha,
a.ContratoId,
a.TotalContrato,
a.Plazo,
a.ValorCuota,
a.Fecha_de_vencimiento
});
var results = resultsQueryable.ToList();
UPDATE:
Since you need to return just Contrato properties, you can further simplify your linq as shown below:
var resultsQueryable = from a in Contrato
join b in Contrato_detalle on a.ContratoId equals b.ContratoId
join c in Contrato_plan_pagos on a.ContratoId equals c.ContratoId
where a.ContratoId < b.ContratoId and a.ContratoId < c.ContratoId
select new {
a.Fecha,
a.ContratoId,
a.TotalContrato,
a.Plazo,
a.ValorCuota,
a.Fecha_de_vencimiento
};
var results = resultsQueryable.ToList();
I have tried to make the following sql in linq with no luck can some help mw with this?
select * from customer c
where companynumber = 1
and status <> 0
and lastdate = (select max(lastdate) from customer where customernumber = c.customernumber)
Gives 22 records
My best try was this:
_ctx.Customers
.Where(r => r.CompanyNumber == companyNumber && r.CustomerNumber != null && r.Status != 0)
.GroupBy(c => c.CustomerNumber)
.Select(g => new
{
name = g.Key,
count = g.Count(),
date = g.Max(x => x.LastEdited)
})
.OrderBy(c => c.name);
Gives 22.000+ records
But not the result as the above SQL
UPDATE:
The following LINQ does the trick ;o)
from a in _ctx.Customers
where a.CustomerNumber != null && a.CompanyNumber == companyNumber
group a by new { a.CustomerNumber } into g
select g.OrderByDescending(a => a.LastEdited).FirstOrDefault() into c
where c.Status == 1
select c
I had to move the where c.Status == 1 into my first select statment
I am having following query & i need to write it in linq. I am stuck in NOT IN part.
SELECT A.CODE,
A.DATETIME,
A.DATE
FROM TABLE_IO A
WHERE A.DATE>= '01/06/2015' AND A.DATE<='01/06/2015'
AND A.CODE NOT IN(
SELECT CODE
FROM TABLE_ENTRY B
WHERE A.CODE=B.CODE AND A.DATE=B.ENTRY_DATE AND METHOD='M'
)
How to write NOT IN part?
var data = ctx.TABLE_IO.Where(m=>m.Date >= '01/06/2015' && m.Date <= '01/06/2015')
.Select(m=>m).ToList();
You can use !Any:
DateTime dateToCompare = new DateTime(2015, 6, 1);
var data = ctx.TABLE_IO
.Where(m => m.Date >= dateToCompare && m.Date <= dateToCompare)
.Where(m => !ctx.TABLE_ENTRY
.Any(te => m.Code == te.Code && m.Date == te.ENTRY_DATE && te.METHOD == "M"))
.ToList();
I would prefer this, i'm fairly sure that it will be translated to a performant NOT EXISTS which has also no issues with null values like NOT IN/Contains.
The direct translation of NOT IN/Contains would be this:
var data = ctx.TABLE_IO
.Where(m => m.Date >= dateToCompare && m.Date <= dateToCompare)
.Where(m => !ctx.TABLE_ENTRY.Select(te => te.Code).Contains(m.Code))
.ToList();
Basically you can do something such as (pseudo queries below)
var exclusions = table_B.Where(b => [exclusion condition] ).Select(b => b.Id)
var data = ctx.TABLE_IO.Where(m => !exclusions.Contains(m.Id))
select c.Name, d.First_Name, COUNT(c.Name) as qty
from order_product_s a
inner join Order_s b on a.Order_Id = b.Id
inner join Product_s c on a.Product_Id = c.Id
inner join Customer_s d on b.Customer_Id = d.Id
where b.Customer_Id = 4869
group by c.Name, d.First_Name
Something like this:
int __UserId = 4869;
var results =
(
from t in
(
from a in Repo.order_product_s
from b in Repo.Order_s
.Where(bb=> bb.id == a.Order_Id)
from c in Repo.Product_s
.Where(cc => cc.Id == a.Product_Id)
from d in Repo.Customer_s
.Where(dd => dd.Id == b.Customer_Id)
where b.Customer_Id == __UserId
select new
{
Name = c.Name
,First_Name = d.First_Name
}
)
group t by new { t.Name , t.First_Name } into g
select new
{
Name = g.Key.Name
,First_Name=g.Key.First_Name
,qty = g.Count( x => x.Name != null)
}
).ToList();
or more compact:
var results =
(
from a in Repo.order_product_s
from b in Repo.Order_s
.Where(bb=> bb.id == a.Order_Id)
// .DefaultIfEmpty() // <== makes join left join
from c in Repo.Product_s
.Where(cc => cc.Id == a.Product_Id)
// .DefaultIfEmpty() // <== makes join left join
from d in Repo.Customer_s
.Where(dd => dd.Id == b.Customer_Id)
// .DefaultIfEmpty() // <== makes join left join
where b.Customer_Id == __UserId
select new
{
Name = c.Name
,First_Name = d.First_Name
}
into t group t by new { t.Name , t.First_Name } into g
select new
{
Name = g.Key.Name
,First_Name=g.Key.First_Name
,qty = g.Count( x => x.Name != null)
// Or like this
// ,qty = g.Select(x => x.Name).Where(x => x != null).Count()
// and if you ever need count(distinct fieldname)
//,qty = g.Select(x => x.GroupName).Where(x => x != null).Distinct().Count()
}
)
// .OrderBy(t => t.Name).ThenBy(t => t.First_Name).ThenBy(t => t.qty) // Order in SQL
.ToList()
// .OrderBy(t => t.Name).ThenBy(t => t.First_Name).ThenBy(t => t.qty) // Order in .NET
;
What is the correct lambda syntax for the following query?
SELECT a.Title, Count(b.Id) FROM a INNER JOIN b on a.Id = b.FK_Id GROUP BY a.Title
I know how to use join, but don't have any idea how to use aggregate and group by in this situation.
Thank you.
Looks to me like:
var query = from a in TableA
join b in TableB on a.Id equals b.FkId
group b by a.Title into g
select new { Title = g.Key, Count = g.Count() };
Or in non-query syntax:
var query = TableA.Join(TableB, a => a.Id, b => b.FkId, (a, b) => new { a, b })
.GroupBy(z => z.a.Title, z => z.b)
.Select(g => new { Title = g.Key, Count = g.Count() });