I have two table as below
Table1
IntervalID(pK)
1
2
3
Table 2
IntervalID Name
1 XXX
Output should be (Table1+Table2)
IntervalID Name
1 XXX
2 NULL
3 NULL
I have done like below
Table1.Merge(Table2);
But it does not give desired output
You could achieve this by using Left join, like the following code:
var result = (from t1 in table1
join t2 in table2 on t1.IntervalId equals t2.IntervalId into leftedResults
from leftedResult in leftedResults.DefaultIfEmpty()
select new { t1.IntervalId, Name = leftedResult?.Name }).ToList();
Note that, you can't merge two DataTables that not have similar schemas.
Left join for DataTables :
var result = (from t1 in dataTable1.AsEnumerable()
join t2 in dataTable2.AsEnumerable() on t1.Field<int>("IntervalId") equals t2.Field<int>("IntervalId") into leftedResults
from leftedReult in leftedResults.DefaultIfEmpty()
select new { IntervalId = t1.Field<int>("IntervalId"), Name = leftedReult?.Field<string>("Name") }).ToList();
I hope you find this helpful.
i am new to LINQ and joins, so Please forgive me if I am asking it wrong.
I have two tables
Table1
id name date
1 Mike 20-10-15
2 John 21-10-15
3 Sam 23-10-15
Table2
id name date
1 Ashle 19-10-15
2 Lily 21-10-15
3 Jeni 22-10-15
4 April 23-10-15
I need 5 records using Joins and should be orderby Date, most recent records.
Can you guys help me, I really need to figure out how Joins works with orderby.
Thanks
EDIT:
They are two different tables so no foreign key, so I think I can't use Join, so so far what I have done is like this
var combinddata = (from t1 in db.Table1
select t1.id)
.Concat(from t2 in db.Table2
select t2.id);
I don't know how to get only 5 records how to compare records from both tables on DateTime base.
Output should be
Sam
April
Jeni
John
Lily
You can concatenate equal anonymous types from different tables. If you also select the dates, you can sort by them, in descending order, and take the first 5 records:
Table1.Select (t1 =>
new
{
Id = t1.Id,
Name = t1.Name,
Date = t1.Date
}
).Concat(
Table2.Select (t2 =>
new
{
Id = t2.Id,
Name = t2.Name,
Date = t2.Date
}
))
.OrderByDescending (x => x.Date).Take(5)
Note that this gives precedence to items in Table1. If item 5 and 6 in the concatenated result are on the same date, but from Table1 and Table2, respectively, you only get the item from Table1.
If you want, you can select only the names from this result, but I assume that your output only shows the intended order of record, not the exact expected result.
var query =
from Table1 in table1
join Table2 in table2 on table1.id equals table2.id
orderby table1.date ascending
select table1.date;
Try this way
var combinddata = (from t1 in db.Table1
select t1.Name)
.Concat(from t2 in db.Table2
select t2.Name).OrderByDescending(x => x.date).Take(5);
I have 3 objects that I need to link together
Parent: TblClients
This will have multiple children of Type TblBusinessLeads , the key between the two is ClientID
Type Lead will have multiple children of type TblFeeBreakouts , the key between the two is LeadID
I have written the following LINQ to get the databack, but it is not coming back (out of memory exception)
from t0 in TblClients
join t1 in TblBusinessLeads on t0.ClientID equals t1.ClientID into t1_join
from t1 in t1_join.DefaultIfEmpty()
join t3 in TblFeeBreakouts on t1.LeadID equals t3.LeadID into t3_join
from t3 in t3_join.DefaultIfEmpty()
orderby
t0.ClientID,
t1.LeadID
select new {
client_data = t0,
business_lead_data = t1_join,
fee_breakout_data = t3_join
}
I am not sure of you can even do this, but the idea seems pretty common. Any help would be greatly appreciated. Thanks
EDIT:
Wow lot of comments. Here goes my answers
I am trying to run the query in LinqPad, thats where the Out of Memory is Occuring
If I look at the SQL generated, it gives me
SELECT [t0].[ClientID], [t0].[ClientName], [t0].[ClientDesc], [t0].[EditedBy], [t0].[EditedDate], [t0].[CreatedBy], [t0].[CreatedDate], [t3].[LeadID], [t3].[InitiativeName], [t3].[Description], [t3].[NewBusNeeds], [t3].[CreativeNeeds], [t3].[IdeationNeeds], [t3].[Comments], [t3].[LossReasons], [t3].[OriginDate], [t3].[DateReceivedAssignment], [t3].[DueDate], [t3].[TimelineNotes], [t3].[PendingCode], [t3].[EstStartDate], [t3].[EstEndDate], [t3].[ExeStartDate], [t3].[ExeEndDate], [t3].[Probable80Total], [t3].[Possible50Total], [t3].[Emerging25Total], [t3].[NoBudget0Total], [t3].[TotalBudget], [t3].[FinancialNotes], [t3].[DollarsRecordFor], [t3].[BizDevContactUserID], [t3].[BizDevContact2UserID], [t3].[SVPContactUserID], [t3].[ClientMgmtContactUserID], [t3].[CMAdditionalContactUserID], [t3].[AdditionalContactUserID], [t3].[CreatorUserID], [t3].[OfficeID], [t3].[ClientID] AS [ClientID2], [t3].[LeadTypeID], [t3].[ActionNeeded], [t3].[ActionDate], [t3].[NewBusDeliveryDate], [t3].[NewBusDesc], [t3].[CreativeDeliveryDate], [t3].[CreativeDesc], [t3].[IdeationDeliveryDate], [t3].[IdeationDesc], [t3].[AltMediaDeliveryDate], [t3].[AltMediaDesc], [t3].[MobileOpsDeliveryDate], [t3].[MobileOpsDesc], [t3].[EventsDeliveryDate], [t3].[EventsDesc], [t3].[Routing], [t3].[RoutingDate], [t3].[Deleted], [t3].[LeadSourceID], [t3].[NatureofLeadID], [t3].[NatureofLeadNotes], [t3].[EditedBy] AS [EditedBy2], [t3].[EditedDate] AS [EditedDate2], [t3].[CreatedBy] AS [CreatedBy2], [t3].[CreatedDate] AS [CreatedDate2], [t3].[ClientContactName], [t3].[ClientContactTitle], [t3].[ReportingYear], (
SELECT COUNT(*)
FROM [tblBusinessLead] AS [t4]
WHERE [t0].[ClientID] = [t4].[ClientID]
) AS [value], [t1].[LeadID] AS [LeadID2]
FROM [tblClient] AS [t0]
LEFT OUTER JOIN [tblBusinessLead] AS [t1] ON [t0].[ClientID] = [t1].[ClientID]
LEFT OUTER JOIN [tblFeeBreakout] AS [t2] ON [t1].[LeadID] = [t2].[LeadID]
LEFT OUTER JOIN [tblBusinessLead] AS [t3] ON [t0].[ClientID] = [t3].[ClientID]
ORDER BY [t0].[ClientID], [t1].[LeadID], [t2].[LeadID], [t2].[FeeTypeID], [t3]. [LeadID]
This returns like 1.2 million rows
There is no mapping in the model becuase the DB has no relationships (they are inferred, no foreign keys or anything like that)
The reason I am using t1_join and t3_join is because if I use t1 or t3, I get the single entity, not the IEnumerable of the object, hence I cant loop over it.
If you have more questions, please ask.
First of all, what possible use could a client have for 1.2 million rows? There is no real good use case for this, so your first step should be figuring out how to filter your results appropriately.
Second, I believe the reason your query is returning OutOfMemoryException is because LinQPad is doing a ToList() or something similar so that I can show the results of the query in the bottom pane. The ToList() is loading all 1.2 million rows into memory. If you ran the query in a regular .Net app, the following will return an IQueryable<> which will not load into memory.
var query =
from t0 in TblClients
join t1 in TblBusinessLeads on t0.ClientID equals t1.ClientID into t1_join
from t1 in t1_join.DefaultIfEmpty()
join t3 in TblFeeBreakouts on t1.LeadID equals t3.LeadID into t3_join
from t3 in t3_join.DefaultIfEmpty()
orderby
t0.ClientID,
t1.LeadID
select new {
client_data = t0,
business_lead_data = t1_join,
fee_breakout_data = t3_join
};
As stated above, it is probably a good idea to setup asociations on these tables, which I did... The LINQ for the result after the association was simple
var clientList = (from a in tblClients
select a).ToList();
From there it was just accessing the properties.
I have two tables in an XML Dataset. T1, T2. Each of the tables has a ID column.
T1 has a list of Customers
T2 has a list of Orders
I want to build a LINQ query that returns only the ID of the customers that do not have orders. In other words customer ID's that do not exist in the T2 table.
Oh yea, I'm using C#
Thanks!
This requires an outer join and a check on null.
var result = from c in Customers
join d in Details on d.CustomerID equals c.ID into g
where !g.Any()
select c;
I think this will work (please adapt to your DataSets):
var query = from c in T1
where !(from o in T2 select o.CustomerID)
.Contains(c.CustomerID)
select c;
You just need to us a where clause and all:
T1.Where( item1 => T2.All( item2 => item1.ID != item2.ID ) );
Is it possible to accomplish something like this using linqtosql?
select * from table t1
left outer join table2 t2 on t2.foreignKeyID=t1.id
left outer join table3 t3 on t3.foreignKeyID=t1.id
I can make it work using both DataLoad options or join syntax. But the problem is whenever I add a second left join, linqtosql queries with MULTIPLE sql statements, instead of doing a second left join in the underlying sql.
So a query like the one above will result in dozens of sql calls instead of one sql call with 2 left joins.
What are my other options? I can use a view in the DB, but now I'm responsible for creating the hierarchy from the flattened list, which is one of the reasons to use an ORM in the first place.
Note that T2 and T3 are 1:M relationships with T1. Is it possible to have linq efficiently query these and return the hierarchy?
I don't think this is likely to be the right solution to your problem because there are more than one many to one relationships to your parent entity table:
select * from table t1
left outer join table2 t2 on t2.foreignKeyID = t1.id
left outer join table3 t3 on t3.foreignKeyID = t1.id
This is like a person with multiple children and multiple vehicles:
Say t1 is the person
id str
1 Me
Say t2 are the children
PK foreignKeyID str
A 1 Boy
B 1 Girl
Say t3 are the vehicles
PK foreignKeyID str
A 1 Ferrari
B 1 Porsche
Your result set is:
Me Boy Ferrari
Me Girl Ferrari
Me Boy Porsche
Me Girl Porcshe
Which I fail to see how this is a useful query (even in SQL).
Here is a similar question. Be cognizant of how the joins are composed.
For example, the following Linq to Sql query on AdventureWorks:
AdventureWorksDataContext db = new AdventureWorksDataContext();
var productStuff = from p in db.Products
join pl in db.ProductListPriceHistories on p.ProductID equals pl.ProductID into plv
from x in plv.DefaultIfEmpty()
join pi in db.ProductInventories on p.ProductID equals pi.ProductID into pii
from y in pii.DefaultIfEmpty()
where p.ProductID == 764
select new { p.ProductID, x.StartDate, x.EndDate, x.ListPrice, y.LocationID, y.Quantity };
Yielded the same SQL (verified via Profiler) as this SQL query:
SELECT Production.Product.ProductID,
Production.ProductListPriceHistory.StartDate,
Production.ProductListPriceHistory.EndDate,
Production.ProductListPriceHistory.ListPrice,
Production.ProductInventory.LocationID,
Production.ProductInventory.Quantity
FROM Production.Product
LEFT OUTER JOIN Production.ProductListPriceHistory ON Production.Product.ProductID = Production.ProductListPriceHistory.ProductID
LEFT OUTER JOIN Production.ProductInventory ON Production.Product.ProductID = Production.ProductInventory.ProductID
WHERE Production.Product.ProductID = 764
Multiple LEFT JOINs on the Primary Key of the parent table, yielding one generated SQL query.
I would think LINQ to SQL would be able to translate your left outer joins as long as you put the DefaultIfEmpty() calls in the right places:
var q = from t1 in table
join t2 in table2 on t1.id equals t2.foreignKeyID into j2
from t2 in j2.DefaultIfEmpty()
join t3 in table3 on t1.id equals t3.foreignKeyID into j3
from t3 in j3.DefaultIfEmpty()
select new { t1, t2, t3 };
You dont need that terrible join syntax if you FK's are properly setup.
You would probably write:
var q = from t1 in dc.table1s
from t2 in t1.table2s.DefaultIfEmpty()
from t3 in t1.table3s.DefaultIfEmpty()
select new { t1, t2, t3 };