Convert LINQ in query syntax to lambda syntax - c#

This is my LINQ query, Please help me in changing this LINQ query to query using Lambda expression:
var query = from d in db.customers
from s in db.tbl_states
where d.cust_state == s.state_id
select new
{
d.cust_name,
s.state_name
};

Try this:
var query =
db.customers.Join (
db.tbl_states,
d => d.cust_state,
s => s.state_id,
(d, s) => new { d.cust_name, s.state_name }
);

This should do it:
var query = db.customers.Join(db.tbl_states, d => d.cust_state, s => s.state_id, (d, s) => new { d.cust_name, s.state_name });

I guess your linq its should be like this
var query = from d in db.customers
join s in db.tbl_states on d.cust_state equals s.state_id
select new
{
d.cust_name,
s.state_name
};
for Lambda
var list = db.customers
.Join(db.tbl_states,
s => s.tbl_states,
d => d.state_id,
(s, d) => new
{
d.cust_name,
s.state_name
});

Related

Lambda syntax. How join by 1 to many keys

i'm trying rewrite query from native sql to linq lambda syntax (not linq query syntax)
LINQ (not work)
var result = _uow.Repository<TableA>().Get().AsNoTracking()
.GroupJoin(
_uow.Repository<TableB>().Get().AsNoTracking(),
a => new { a.TabNotesCodeId, a.TabLabelCodeId },
b => b.ElementNameId
(b, a) => new SubSection
{
SubSectionName = b.CustomValue ?? a.TabLabelCodeId,
SubSectionNote = b.CustomValue ?? a.TabLabelCodeId,
})
.Where(a => a.ResourceId == 1);
SQL
SELECT [SubSectionName] = ISNULL(B.CUSTOMVALUE,A.TABLABELCODEID),
[SubSectionNote] = ISNULL(B.CUSTOMVALUE,A.TABNOTESCODEID)
FROM TableA as A LEFT JOIN
(SELECT CUSTOMVALUE, ELEMENTNAMEID FROM TableB WHERE DISPLAYSETTINGID = 1) as B
ON B.ELEMENTNAMEID IN ( A.TABNOTESCODEID, A.TABLABELCODEID)
WHERE A.RESOURCEID = 1
Q How to rewrite sql ON B.ELEMENTNAMEID IN ( A.TABNOTESCODEID, A.TABLABELCODEID) to lambda syntax
...
a => new { a.TabNotesCodeId, a.TabLabelCodeId },
b => b.ElementNameId
....
(doesn't work)
Normally I would suggest following my SQL conversion rules, but this is sufficiently complex I don't think it would help.
To use query comprehension syntax on a non-equijoin that is a left join, it seems easiest to use lambda syntax to express the join conditions, so I just combined the sub-query with the join conditions:
var ans = from A in TableA
where A.ResourceID == 1
from B in TableB.Where(b => b.DisplaySettingID == 1).Where(b => b.ElementNameID == A.TabNotesCodeID || b.ElementNameID == A.TabLabelCodeID).DefaultIfEmpty()
select new {
SubSectionName = (B.CustomValue ?? A.TabLabelCodeID),
SubSectionNote = (B.CustomValue ?? A.TabNotesCodeID)
};
The lambda equivalent of multiple from clauses to generate a cross join is SelectMany, so converting into lambda syntax:
var ans2 = TableA.Where(a => a.ResourceID == 1)
.SelectMany(a => TableB.Where(b => b.DisplaySettingID == 1).Where(b => b.ElementNameID == a.TabNotesCodeID || b.ElementNameID == a.TabLabelCodeID)
.DefaultIfEmpty(),
(a, b) => new {
SubSectionName = (b.CustomValue ?? a.TabLabelCodeID),
SubSectionNote = (b.CustomValue ?? a.TabNotesCodeID)
}
);
After countless experiments i've found out solution:
_uow.Repository<TableA>().Get().AsNoTracking()
.GroupJoin(
_uow.Repository<TableB>().Get().AsNoTracking().Where(b => b.DisplaySettingId == 1),
a => new { note = a.TabNotesCodeId, label = a.TabLabelCodeId },
b => new { note = b.ElementNameId, label = b.ElementNameId },
(a, b) => new { a,b })
.Where(joinTables => joinTables.a.ResourceId == 1)
.SelectMany(
joinTables => joinTables.b.DefaultIfEmpty(),
(joinTables, b) => new SubSection()
{
LayoutTab = joinTables.a.LayoutTab,
SubSectionName = b.CustomValue ?? joinTables.a.TabLabelCodeId,
SubSectionNote = b.CustomValue ?? joinTables.a.TabNotesCodeId
});

SQL query to LINQ conversion with nested select statements

I want to convert the following query to LINQ:
SELECT LV.* FROM LowerVehicles LV
INNER JOIN (Select VSerial,MAX(updatedOn) MaxUpdatedOn from LowerVehicles group by vserial) LVG
ON LV.VSerial = LVG.VSerial AND LV.updatedOn = LVG.MaxUpdatedOn
Not knowing your entities classes, here is an approximation. You can use query syntax or fluent syntax. Sometimes one is preferable over the other, and in the case of joins and grouping I prefer to use query syntax.
QUERY SYNTAX
var query = from LV in LowerVehicles
join LVG in (
from r in LowerVehicles
group r by r.vserial into g
select new {VSerial = g.Key, MaxUpdatedOn = g.Max(t => t.updatedOn)})
on LV.VSerial equals LVG.Vserial
and LV.updatedOn equals LVG.MaxUpdatedOn
select LV;
FLUENT SYNTAX
var lvg = LowerVehicles.GroupBy(t => t.vserial)
.Select(g => new {
VSerial = g.Key,
MaxUpdatedOn = g.Max(t => t.updatedOn)
});
var query = LowerVehicles.Join(
lvg,
a => new { a.VSerial, a.updatedOn },
b => new { b.VSerial, b.MaxUpdatedOn },
(a, b) => new { LV = a, LVG = b}
)
.Select(t=> t.LV);
Something like this?
Something.LowerVehicles
.Join(something.LowerVehicles.Select(y => new { y.VSerial, updatedOn = y.updatedOn.Max() }).GroupBy(z => z.VSerial),
x => new { x.VSerial, x.updatedOn },
lvg => new { lvg.VSerial, lvg.updatedOn },
(x, y) => x)

How to convert following SQL Query into Lambda Expression?

I have a following SQL Query, which i have converted to Linq, and don't know how can i Convert this query into Lambda Expression.
SQL
SELECT BP.*
FROM [ams].[BackgroundPackage] AS BP
INNER JOIN [ams].[BkgPackageHierarchyMapping] AS BPHM
ON BP.BPA_ID = BPHM.BPHM_BackgroundPackageID
INNER JOIN [ams].[BkgOrderPackage] AS BOP
ON BPHM.BPHM_ID = BOP.BOP_BkgPackageHierarchyMappingID
INNER JOIN [ams].[BkgOrder] AS BO ON BOP.BOP_BkgOrderID = BO.BOR_ID
WHERE BO.BOR_MasterOrderID = #OrderID
AND BO.BOR_IsDeleted = 0
Lambda Version
// how to write lambda version of above query
Linq Version
var packageData =
(from ep in _dbContext.BackgroundPackages
join e in _dbContext.BkgPackageHierarchyMappings on ep.BPA_ID equals e.BPHM_BackgroundPackageID
join t in _dbContext.BkgOrderPackages on e.BPHM_ID equals t.BOP_BkgPackageHierarchyMappingID
join s in _dbContext.BkgOrders on t.BOP_BkgOrderID equals s.BOR_ID
where s.BOR_MasterOrderID == orderId
select new
{
Id = ep.BPA_ID,
Name = ep.BPA_Name,
});
the lambda query (concise notation) for your SQL would be:
var lambdaQuery = _dbContext.BackgroundPackages
.Join(_dbContext.BkgPackageHierarchyMappings, ep => ep.BPA_ID, e => e.BPHM_BackgroundPackageID, (ep, e) => ep)
.Join(_dbContext.BkgOrderPackages, ep => ep.BPHM_ID, t => t.BOP_BkgPackageHierarchyMappingID, (ep, t) => new { ep, t})
.Join(_dbContext.BkgOrders, ept => ept.t.BOP_BkgOrderID, s => s.BOR_ID, (ept, s) => new { ept.ep, s })
.Where(eps => eps.s.BOR_MasterOrderID == orderId && eps.s.BOR_IsDeleted == 0)
.Select(eps => eps.ep);

Group By using Select statement in Linq

var query = from i in SFC.Supplies_ReceiveTrans
orderby i.Poprctnm descending
select new { RR = i.Poprctnm };
Result:
RR-01,
RR-01,
RR-02,
RR-02,
RR-02,
RR-TEST,
RR-TEST,
How do i group RR in this kind of statement
Result:
RR-01,
RR-02,
RR-TEST
just a few modification to ask if is it possible to do this one or what you have in your mind? Sorry for asking too much just really interested in learning more on linq.. how do i convert it into string coz its showing true or false.. boolean statement
var query = SFC.Supplies_ReceiveTrans.Select(s =>
s.Poprctnm.StartsWith(p))
.Distinct()
.OrderBy(p => p)
.Select(p => new { RR = p })
.Take(10);
You can use Distinct or GroupBy methods in this case
var query = SFC.Supplies_ReceiveTrans.Select(s=> s.Poprctnm)
.Distinct()
.OrderByDescending(p => p)
.Select(p=> new { RR = p });
if you use OrderByDescending then the result will be
RR-TEST
RR-02
RR-01
But I think you want OrderBy then the result will be
RR-01
RR-02
RR-TEST
So try below
var query = SFC.Supplies_ReceiveTrans.Select(s=> s.Poprctnm)
.Distinct()
.OrderBy(p => p)
.Select(p=> new { RR = p });
var query = SFC.Supplies_ReceiveTrans
.GroupBy(x=>x.Poprctnm)
.Select(g=>g.First())
.OrderByDescending(x=>x.Poprctnm)
.Select(x=>new { RR = x.Poprctnm });
If you want to get result as group:
var query = SFC.Supplies_ReceiveTrans
.GroupBy(x=>x.Poprctnm)
.OrderByDescending(g=>g.Key);
var result = SFC.Supplies_ReceiveTrans
.Select(x => new { RR = x.Poprctnm })
.Distinct()
.OrderByDescending(x => x.Poprctnm);
Looks like you need Distinct here, not group
var query = SFC.Supplies_ReceiveTrans
.Select(x => new {RR = i.Poprctnm})
.Distinct()
.OrderByDescending(i => i);

Left outer join of datatable with linq expression?

I have two DataTables:
DataTable dtFields = new DataTable("tmpFieldTable");
dtFields.Columns.Add("FieldID");
dtFields.Columns.Add("CDGroupID");
dtFields.Columns.Add("CDCaption");
dtFields.Columns.Add("fldIndex");
and
DataTable dtCDGroup = new DataTable("tmpCDGroup");
dtCDGroup.Columns.Add("CDGroupID");
dtCDGroup.Columns.Add("Name");
dtCDGroup.Columns.Add("Priority");
I am using following LINQ expression to join these tables:
var resultList = dtFields.AsEnumerable()
.Join(dtCDGroup.AsEnumerable(),
fieldList => fieldList.Field<string>("CDGroupID"),
cd => cd.Field<string>("CDGroupID"),
(fieldList, cd) => new
{
FieldID = fieldList.Field<string>("FieldID"),
CdGroup = cd.Field<string>("Name"),
CDCaption = fieldList.Field<string>("CDCaption"),
Priority = (cd.Field<string>("Priority") ?? "99"),
fldIndex = fieldList.Field<string>("fldIndex").ToString()
})
.OrderBy(result => result.Priority)
.ThenBy(result => result.fldIndex);
How can I perform left outer join with these DataTables?
Left join are not natively offered using lambda expression. but you can achieve this using GroupJoin and SelectMany method.
var result = new string[] { "A", "B" }.GroupJoin(new string[] { "B" }, l => l, r => r, (l, r) => new { l, r }).ToList();
Console.WriteLine(result.Count());
this will result result[0].r.Count() = 0 and result[1].r.Count() = 1.
Hope this will help.
Regards.
Just add DefaultIfEmpty() to your table:
resultList = dtFields.AsEnumerable()
.Join(dtCDGroup.AsEnumerable().DefaultIfEmpty(),
fieldList => fieldList.Field<string>("CDGroupID"),
cd => cd.Field<string>("CDGroupID"),
(fieldList, cd) => new
{
FieldID = fieldList.Field<string>("FieldID"),
CdGroup = cd.Field<string>("Name"),
CDCaption = fieldList.Field<string>("CDCaption"),
Priority = (cd.Field<string>("Priority") ?? "99"),
fldIndex = fieldList.Field<string>("fldIndex").ToString()
})
.OrderBy(result => result.Priority)
.ThenBy(result => result.fldIndex);

Categories