Combining Querys - c#

I am using Linq to Sql to get two lists than take Union with another list. They are working fine. But I am wondering if it can be done in one Query or two instead of three that I have.
Querys are
var l = (from t in T_list1
where t.Date == DateTime.Today
select new
{
oldDate=t.OldDate,
Name=t.name,
Email=t.EmailAddress,
list2TableId=t.l2Id,
CustomerId=t.customerId
});
var l2=(from d in T_list2
from e in l1
where d.Id == e.list2TableId
select new
{
Date=d.oldDate,
CName=d.Name,
Experience=e.experience,
});
list2.Dump();
var l3 = list2.Union(list3).ToList();
I was looking at this post but didnt work. Combining 2 Linq queries into 1
Thanks for your input.

You could do a join instead of the 2 queries:
var l = (from t in T_list1
join d in T_list2 on t.l2Id equals d.Id
where t.Date == DateTime.Today
select new
{
oldDate=t.OldDate,
Name=t.name,
Email=t.EmailAddress,
list2TableId=t.l2Id,
CustomerId=t.customerId
Date=d.oldDate,
CName=d.Name
Experience=e.experience,
});
I haven't tested the query but it should show you the rough idea.
Have a look at JOINs in SQL & Linq to get more information.

Related

order by len() but in linq with c#

this is my query in sql server and everything works fine
select * from DetalleNotas
order by len(ColProduct), ColProduct
PROCT1
PROCT2
PROCT3
PROCT4
PROCT5
PROCT6
PROCT7
PROCT8
PROCT9
PROCT10
but i want my query in linq c#
I tried this and it does not work
var product = (from d in db.Product
orderby len(d.ColProduct), d.ColProduct
select new
{
product= d.product
});
the name "len" does not exist in the real context
only this query works
var product = (from d in db.DetalleNotas
orderby d.ColProduct
select new
{
product= d.product
});
This is the result of my functional query
PROCT1
PROCT10
PROCT2
PROCT3
PROCT4
PROCT5
PROCT6
PROCT7
PROCT8
PROCT9
Remember that in C# Linq code, everything is still C#. As you're working with strings you need to order by string.Length. For example:
var results = from d in db.DetalleNotas
orderby d.ColProduct.Length
select d;
You could order it by the number on the end of your strings:
var result = db.DetalleNotas.OrderBy(d => Convert.ToInt32(d.ColProduct.Substring(5)))
.ToArray();

LINQ Select newest records that have distinct ForeignKeyId column

I have the following SQL query:
SELECT
table1.Id AS EinAusgangId,
table1.Ausgabedatum,
table1.Rueckgabedatum,
table1.WerkzeugId,
cpmWerkzeug.Name
FROM cpmEinAusgang AS table1
INNER JOIN cpmWerkzeug ON table1.WerkzeugId = cpmWerkzeug.Id
WHERE table1.Id = (SELECT MAX(Id) AS Expr1
FROM dbo.cpmEinAusgang
WHERE table1.WerkzeugId = WerkzeugId)
My aim is to convert the whole query into a LINQ statement for further use in a .Net Application. I already converted joined tables to LINQ but is it also possible to use a select in the where clause?
This is what I got so far, which gives me almost the same result as the SQL statement above, but has major errors when the table cpmEinAusgang contains more then one record for one cpmWerkzeug
using (var dbContext = new cpmEntities())
{
var werkzeuge = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where e.Rueckgabedatum == null
orderby w.Name
select w;
return werkzeuge.ToList();
}
Has anyone an idea how to achieve the above sql in linq?
Thanks for your help. :)
EDIT:solved (see below)
var werkzeugeImUmlauf = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where e.Id == dbContext.cpmEinAusgang.Where(x => x.WerkzeugId == e.WerkzeugId).Max(x => x.Id) select w;
This is the final solution. As mentioned by Mittal in his answer, it is possible to write a sub-query in LINQ.
Yes, you can write Sub Query in LINQ as well.
var werkzeuge = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where w.id = (dbContext.cpmEinAusgang.Max(x => x.id)) AND w.WerkzeugId = WerkzeugId

getting error in joining dictionary with table

I want to have join query from a table with a dictionary based on a common field, my query is:
var query = from c in db.Exp
join d in lstUniprotDic on c.UniID equals d.Key
select new
{
c.UniID,
IdentityPercent=d.Value.ToString(),
c.PrId,
c.SpotNo
}
but i got the following error
Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.
That pretty much says it all. You can't use the dictionary in your LINQ to SQL query except when using Contains.
Solution:
(from c in db.Exp where lstUniprotDic.Keys.Contains(c.UniID) select c).AsEnumerable()
join d in lstUniprotDic on c.UniID equals d.Key
select new
{
c.UniID,
IdentityPercent=d.Value.ToString(),
c.PrId,
c.SpotNo
}
I am not sure if the usage of lstUniprotDic.Keys in the LINQ to SQL query is actually working.
If not, try using this code instead:
var ids = lstUniprotDic.Keys.ToArray();
(from c in db.Exp where ids.Contains(c.UniID) select c).AsEnumerable()
join d in lstUniprotDic on c.UniID equals d.Key
select new
{
c.UniID,
IdentityPercent=d.Value.ToString(),
c.PrId,
c.SpotNo
}

convert trans-sql to LINQ LEFT JOIN and Where Clause

How would you convert this trans-sql to LINQ?
I've tried it with the DefaultIfEmpty() but it seems to not be working for me.
Any help is appreciated.
SELECT s.Status
FROM EducationModule M
LEFT JOIN EducationModuleStatus S ON M.CourseID = S.CourseID
AND M.ModuleID = S.ModuleID
AND S.StudentID = '1506'
WHERE M.courseid = 2
Thanks in advance.
Joining on multiple columns in Linq to SQL is a little different.
You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against, and under the sheet this will generate the type of join you are looking for.
var abcd = from tl in db.EducationModule
join s in db.EducationModuleStatus
on new { t1.CourseID, t1.ModuleID } equals new {s.CourseID, s.ModuleID}
into tl_s
where tl.CourseID == 2 AND s.StudentID == '1506'
from s in tl_s.DefaultIfEmpty()
select new
{
Status = s.Status
};

using "greater than or equal" operator in linq join operation [duplicate]

I had tried to join two table conditionally but it is giving me syntax error. I tried to find solution in the net but i cannot find how to do conditional join with condition. The only other alternative is to get the value first from one table and make a query again.
I just want to confirm if there is any other way to do conditional join with linq.
Here is my code, I am trying to find all position that is equal or lower than me. Basically I want to get my peers and subordinates.
from e in entity.M_Employee
join p in entity.M_Position on e.PostionId >= p.PositionId
select p;
You can't do that with a LINQ joins - LINQ only supports equijoins. However, you can do this:
var query = from e in entity.M_Employee
from p in entity.M_Position
where e.PostionId >= p.PositionId
select p;
Or a slightly alternative but equivalent approach:
var query = entity.M_Employee
.SelectMany(e => entity.M_Position
.Where(p => e.PostionId >= p.PositionId));
Following:
from e in entity.M_Employee
from p in entity.M_Position.Where(p => e.PostionId >= p.PositionId)
select p;
will produce exactly the same SQL you are after (INNER JOIN Position P ON E..PostionId >= P.PositionId).
var currentDetails = from c in customers
group c by new { c.Name, c.Authed } into g
where g.Key.Authed == "True"
select g.OrderByDescending(t => t.EffectiveDate).First();
var currentAndUnauthorised = (from c in customers
join cd in currentDetails
on c.Name equals cd.Name
where c.EffectiveDate >= cd.EffectiveDate
select c).OrderBy(o => o.CoverId).ThenBy(o => o.EffectiveDate);
If you have a table of historic detail changes including authorisation status and effective date. The first query finds each customers current details and the second query adds all subsequent unauthorised detail changes in the table.
Hope this is helpful as it took me some time and help to get too.

Categories

Resources