I have 2 C# datatable:
Datatable A:
id
Name
Age
Height
01
Pauls
22
170
02
Sam
20
175
03
Mike
20
175
04
Jame
23
180
Datatable B:
id
Height
Age
01
175
23
02
190
21
The question here is how could I get this output by join 2 table A & B by id and get output datatable using Linq in C# OutputTable:
id
Name
Age
Height
01
Pauls
23(value in table B)
175 (value in table B)
02
Sam
21(value in table B)
190 (value in table B)
03
Mike
20
175
04
Jame
23
180
My code here:
var results = from ta in tableA.AsEnumerable()
join tb in tableB.AsEnumerable on ta["id"] equals tb["id"]
select new
{
ta["id"],
ta["Name"],
tb["Age"],
tb["Height"]
};
My output so far (not what I expected):
id
Name
Age
Height
01
Pauls
23(value in table B)
175 (value in table B)
02
Sam
21(value in table B)
190 (value in table B)
P/s: above table is just an example data, true data is bigger
INNER JOIN works as filter if record not found on the right side. You have to use LEFT JOIN here, which is implemented in LINQ as GroupJoin with SelectMany:
var results = from ta in tableA
join tb in tableB on ta.id equals tb.id into g
from tb in g.DefaultIfEmpty()
select new
{
ta.id,
ta.Name,
Age = tb != null ? tb.Age : ta.Age,
Height = tb != null ? tb.Height : ta.Height,
};
Could you try something like this:
var results = from ta in tableA
join tb in tableB on ta.id equals tb.id into gj
from subTableA in gj.DefaultIfEmpty()
select new
{
id = ta.id,
Name = ta.Name,
Age = (subTableA == null ? ta.Age : tb.Age + "(value in table B)"),
Height = (subTableA == null ? ta.Height : tb.Height + "(value in table B)")
};
Here is some page about left join using Entity Framework - https://learn.microsoft.com/en-us/dotnet/csharp/linq/perform-left-outer-joins
Idea is to introduce row 'from subTableA in gj.DefaultIfEmpty()' in order to get all rows from the join, even those which don't have matching value in second table.
If I understand the question correctly, you want to get back a DataTable from your LINQ query. However, LINQ returns an IEnumerable<T> or an IQueryable<T> if you're querying a database.
If you want a DataTable, you'll need some additional code. I suggest you refer to the top answer on this StackOverflow question, which provides a solution for converting an IEnumerable to a DataTable.
I've got a very strange behaviour in LINQ joins
I'm joining a IEnumerable collection and a view which i'm accessing through Entity Framework.
For example (numbers are column values):
Collection
1 1
1 2
View
1 3
1 4
Result of a join should be
1 1 1 3
1 1 1 4
1 2 1 3
1 2 1 4
And i get that result in T-SQL in managment studio and even using the same code in LinqPad,
but in VS i get
1 1 1 3
1 1 1 3
1 2 1 3
1 2 1 3
or
1 1 1 4
1 1 1 4
1 2 1 4
1 2 1 4
but never the correct join. I check Linq generated query through SQL Server Profiler and launched it in Managment Stuiod, and got the correct answer. Please help me to understand such very strange behaviour
var allocations = InvoicingContext.vAllocations.Where(x => auditIds.Contains(x.AuditGroupId.Value)).AsEnumerable();
var q = from a in allocations
join c in CommonCodesContext.vContainerEntity on a.ContainerId equals c.ContainerId
select new ContainerServiceModel
{
ContainerNo = a.ContainerNo,
PortATD = c.ATD,
ATA_KL = a.ServiceDate,
RateWithoutVat = a.RateWithoutVat,
DestinationCityId = c.DestinationCityId,
Quantity = 1
};
var containerServiceModels = q.ToList();
int destinationCount = containerServiceModels.Where(x => x.DestinationCityId == 14).Count();
Queries generated for Linq code (Visual Studio)
SELECT
[Extent1].[ShipperID] AS [ShipperID],
[Extent1].[CarrierId] AS [CarrierId],
[Extent1].[ShippingLineID] AS [ShippingLineID],
[Extent1].[TerminalId] AS [TerminalId],
[Extent1].[Terminal] AS [Terminal],
[Extent1].[ContainerId] AS [ContainerId],
[Extent1].[ContainerNo] AS [ContainerNo],
[Extent1].[ContTypeID] AS [ContTypeID],
[Extent1].[PortStorageDays] AS [PortStorageDays],
[Extent1].[UnloadDate] AS [UnloadDate],
[Extent1].[ATA] AS [ATA],
[Extent1].[ATD] AS [ATD],
[Extent1].[PortShipped] AS [PortShipped],
[Extent1].[IsSealed] AS [IsSealed],
[Extent1].[ATA_CY] AS [ATA_CY],
[Extent1].[ATD_CY] AS [ATD_CY],
[Extent1].[InspectionDate] AS [InspectionDate],
[Extent1].[OrderId] AS [OrderId],
[Extent1].[OrderTypeId] AS [OrderTypeId],
[Extent1].[StorageTypeId] AS [StorageTypeId],
[Extent1].[LoadRegionId] AS [LoadRegionId],
[Extent1].[LoadCityId] AS [LoadCityId],
[Extent1].[DestinationRegionId] AS [DestinationRegionId],
[Extent1].[DestinationCityId] AS [DestinationCityId],
[Extent1].[ODCYCustomer] AS [ODCYCustomer],
[Extent1].[ODCYShipped] AS [ODCYShipped],
[Extent1].[PortReturnDate] AS [PortReturnDate],
[Extent1].[IsReturnedToPort] AS [IsReturnedToPort],
[Extent1].[ODCYStorageDays] AS [ODCYStorageDays],
[Extent1].[DetentionDays] AS [DetentionDays],
[Extent1].[CCFinish] AS [CCFinish],
[Extent1].[FreeDaysForTrucker] AS [FreeDaysForTrucker],
[Extent1].[TruckingUnloadDays] AS [TruckingUnloadDays],
[Extent1].[TruckingEmptyReturnDays] AS [TruckingEmptyReturnDays],
[Extent1].[TruckingEmptyReturnDetentionDays] AS [TruckingEmptyReturnDetentionDays],
[Extent1].[LatePickUpDays] AS [LatePickUpDays]
FROM (SELECT
[vContainerEntity].[ShipperID] AS [ShipperID],
[vContainerEntity].[CarrierId] AS [CarrierId],
[vContainerEntity].[ShippingLineID] AS [ShippingLineID],
[vContainerEntity].[TerminalId] AS [TerminalId],
[vContainerEntity].[Terminal] AS [Terminal],
[vContainerEntity].[ContainerId] AS [ContainerId],
[vContainerEntity].[ContainerNo] AS [ContainerNo],
[vContainerEntity].[ContTypeID] AS [ContTypeID],
[vContainerEntity].[PortStorageDays] AS [PortStorageDays],
[vContainerEntity].[UnloadDate] AS [UnloadDate],
[vContainerEntity].[ATA] AS [ATA],
[vContainerEntity].[ATD] AS [ATD],
[vContainerEntity].[PortShipped] AS [PortShipped],
[vContainerEntity].[IsSealed] AS [IsSealed],
[vContainerEntity].[ATA_CY] AS [ATA_CY],
[vContainerEntity].[ATD_CY] AS [ATD_CY],
[vContainerEntity].[InspectionDate] AS [InspectionDate],
[vContainerEntity].[OrderId] AS [OrderId],
[vContainerEntity].[OrderTypeId] AS [OrderTypeId],
[vContainerEntity].[StorageTypeId] AS [StorageTypeId],
[vContainerEntity].[LoadRegionId] AS [LoadRegionId],
[vContainerEntity].[LoadCityId] AS [LoadCityId],
[vContainerEntity].[DestinationRegionId] AS [DestinationRegionId],
[vContainerEntity].[DestinationCityId] AS [DestinationCityId],
[vContainerEntity].[ODCYCustomer] AS [ODCYCustomer],
[vContainerEntity].[ODCYShipped] AS [ODCYShipped],
[vContainerEntity].[PortReturnDate] AS [PortReturnDate],
[vContainerEntity].[IsReturnedToPort] AS [IsReturnedToPort],
[vContainerEntity].[ODCYStorageDays] AS [ODCYStorageDays],
[vContainerEntity].[DetentionDays] AS [DetentionDays],
[vContainerEntity].[CCFinish] AS [CCFinish],
[vContainerEntity].[FreeDaysForTrucker] AS [FreeDaysForTrucker],
[vContainerEntity].[TruckingUnloadDays] AS [TruckingUnloadDays],
[vContainerEntity].[TruckingEmptyReturnDays] AS [TruckingEmptyReturnDays],
[vContainerEntity].[TruckingEmptyReturnDetentionDays] AS [TruckingEmptyReturnDetentionDays],
[vContainerEntity].[LatePickUpDays] AS [LatePickUpDays]
FROM [Tariff].[vContainerEntity] AS [vContainerEntity]) AS [Extent1]
and
SELECT
[Extent1].[id] AS [id],
[Extent1].[Payer] AS [Payer],
[Extent1].[Receiver] AS [Receiver],
[Extent1].[CustomerId] AS [CustomerId],
[Extent1].[CustomerName] AS [CustomerName],
[Extent1].[AuditGroupId] AS [AuditGroupId],
[Extent1].[ContainerId] AS [ContainerId],
[Extent1].[OrderId] AS [OrderId],
[Extent1].[ContainerNo] AS [ContainerNo],
[Extent1].[TariffId] AS [TariffId],
[Extent1].[ServiceTypeId] AS [ServiceTypeId],
[Extent1].[ServiceType] AS [ServiceType],
[Extent1].[ServiceDate] AS [ServiceDate],
[Extent1].[IsServiceDateClosed] AS [IsServiceDateClosed],
[Extent1].[InvoiceId] AS [InvoiceId],
[Extent1].[InvoiceNo] AS [InvoiceNo],
[Extent1].[InvoiceDate] AS [InvoiceDate],
[Extent1].[ReceiveDate] AS [ReceiveDate],
[Extent1].[DueDate] AS [DueDate],
[Extent1].[ResponsibleUser] AS [ResponsibleUser],
[Extent1].[Free] AS [Free],
[Extent1].[PaymentQty] AS [PaymentQty],
[Extent1].[RateWithoutVat] AS [RateWithoutVat],
[Extent1].[RateWithVat] AS [RateWithVat],
[Extent1].[AmountWithoutVat] AS [AmountWithoutVat],
[Extent1].[CommissionWithoutVat] AS [CommissionWithoutVat],
[Extent1].[TotalAmountWithoutVat] AS [TotalAmountWithoutVat],
[Extent1].[AmountWithVat] AS [AmountWithVat],
[Extent1].[CommissionWithVat] AS [CommissionWithVat],
[Extent1].[TotalAmountWithVat] AS [TotalAmountWithVat],
[Extent1].[VatSum] AS [VatSum],
[Extent1].[RateWithoutVatRub] AS [RateWithoutVatRub],
[Extent1].[RateWithVatRub] AS [RateWithVatRub],
[Extent1].[AmountWithoutVatRub] AS [AmountWithoutVatRub],
[Extent1].[CommissionAmountWithoutVatInRub] AS [CommissionAmountWithoutVatInRub],
[Extent1].[TotalAmountWithoutVatRub] AS [TotalAmountWithoutVatRub],
[Extent1].[AmountWithVatRub] AS [AmountWithVatRub],
[Extent1].[CommissionAmountWithVatInRub] AS [CommissionAmountWithVatInRub],
[Extent1].[TotalAmountWithVatRub] AS [TotalAmountWithVatRub],
[Extent1].[AmountVatRub] AS [AmountVatRub],
[Extent1].[CommissionVatRub] AS [CommissionVatRub],
[Extent1].[VatSumInRub] AS [VatSumInRub],
[Extent1].[CurrencyId] AS [CurrencyId],
[Extent1].[IncludeVat] AS [IncludeVat],
[Extent1].[VAT] AS [VAT],
[Extent1].[IncludeVatInCommission] AS [IncludeVatInCommission],
[Extent1].[ExchangeDate] AS [ExchangeDate],
[Extent1].[ExchangeDateForCommission] AS [ExchangeDateForCommission],
[Extent1].[ExchangeRate] AS [ExchangeRate],
[Extent1].[CommissionExchangeRate] AS [CommissionExchangeRate],
[Extent1].[AverageExchangeRate] AS [AverageExchangeRate],
[Extent1].[StatusId] AS [StatusId],
[Extent1].[Remark] AS [Remark],
[Extent1].[Author] AS [Author],
[Extent1].[DtCreated] AS [DtCreated]
FROM (SELECT
[vAllocations].[id] AS [id],
[vAllocations].[Payer] AS [Payer],
[vAllocations].[Receiver] AS [Receiver],
[vAllocations].[CustomerId] AS [CustomerId],
[vAllocations].[CustomerName] AS [CustomerName],
[vAllocations].[AuditGroupId] AS [AuditGroupId],
[vAllocations].[ContainerId] AS [ContainerId],
[vAllocations].[OrderId] AS [OrderId],
[vAllocations].[ContainerNo] AS [ContainerNo],
[vAllocations].[TariffId] AS [TariffId],
[vAllocations].[ServiceTypeId] AS [ServiceTypeId],
[vAllocations].[ServiceType] AS [ServiceType],
[vAllocations].[ServiceDate] AS [ServiceDate],
[vAllocations].[IsServiceDateClosed] AS [IsServiceDateClosed],
[vAllocations].[InvoiceId] AS [InvoiceId],
[vAllocations].[InvoiceNo] AS [InvoiceNo],
[vAllocations].[InvoiceDate] AS [InvoiceDate],
[vAllocations].[ReceiveDate] AS [ReceiveDate],
[vAllocations].[DueDate] AS [DueDate],
[vAllocations].[ResponsibleUser] AS [ResponsibleUser],
[vAllocations].[Free] AS [Free],
[vAllocations].[PaymentQty] AS [PaymentQty],
[vAllocations].[RateWithoutVat] AS [RateWithoutVat],
[vAllocations].[RateWithVat] AS [RateWithVat],
[vAllocations].[AmountWithoutVat] AS [AmountWithoutVat],
[vAllocations].[CommissionWithoutVat] AS [CommissionWithoutVat],
[vAllocations].[TotalAmountWithoutVat] AS [TotalAmountWithoutVat],
[vAllocations].[AmountWithVat] AS [AmountWithVat],
[vAllocations].[CommissionWithVat] AS [CommissionWithVat],
[vAllocations].[TotalAmountWithVat] AS [TotalAmountWithVat],
[vAllocations].[VatSum] AS [VatSum],
[vAllocations].[RateWithoutVatRub] AS [RateWithoutVatRub],
[vAllocations].[RateWithVatRub] AS [RateWithVatRub],
[vAllocations].[AmountWithoutVatRub] AS [AmountWithoutVatRub],
[vAllocations].[CommissionAmountWithoutVatInRub] AS [CommissionAmountWithoutVatInRub],
[vAllocations].[TotalAmountWithoutVatRub] AS [TotalAmountWithoutVatRub],
[vAllocations].[AmountWithVatRub] AS [AmountWithVatRub],
[vAllocations].[CommissionAmountWithVatInRub] AS [CommissionAmountWithVatInRub],
[vAllocations].[TotalAmountWithVatRub] AS [TotalAmountWithVatRub],
[vAllocations].[AmountVatRub] AS [AmountVatRub],
[vAllocations].[CommissionVatRub] AS [CommissionVatRub],
[vAllocations].[VatSumInRub] AS [VatSumInRub],
[vAllocations].[CurrencyId] AS [CurrencyId],
[vAllocations].[IncludeVat] AS [IncludeVat],
[vAllocations].[VAT] AS [VAT],
[vAllocations].[IncludeVatInCommission] AS [IncludeVatInCommission],
[vAllocations].[ExchangeDate] AS [ExchangeDate],
[vAllocations].[ExchangeDateForCommission] AS [ExchangeDateForCommission],
[vAllocations].[ExchangeRate] AS [ExchangeRate],
[vAllocations].[CommissionExchangeRate] AS [CommissionExchangeRate],
[vAllocations].[AverageExchangeRate] AS [AverageExchangeRate],
[vAllocations].[StatusId] AS [StatusId],
[vAllocations].[Remark] AS [Remark],
[vAllocations].[Author] AS [Author],
[vAllocations].[DtCreated] AS [DtCreated]
FROM [dbo].[vAllocations] AS [vAllocations]) AS [Extent1]
WHERE ([Extent1].[AuditGroupId] IN (9107)) AND ([Extent1].[AuditGroupId] IS NOT NULL)
Queries generated on LinqPAD test
exec sp_executesql N'SELECT [t0].[ContainerNo], [t1].[ATD] AS [PortATD], [t0].[ServiceDate] AS [ATA_KL], [t0].[RateWithoutVat], [t1].[DestinationCityId]
FROM [Invoicing_SPB].[dbo].[vAllocations] AS [t0]
INNER JOIN [Tariff].[vContainerEntity] AS [t1] ON ([t0].[ContainerId]) = [t1].[ContainerId]
WHERE ([t1].[DestinationCityId] = #p0) AND ([t0].[AuditGroupId] = #p1)',N'#p0 int,#p1 int',#p0=14,#p1=9107
I've tried to loop and get count of result collection dependting on predicate
Invoicing_SPBEntities invContext = new Invoicing_SPBEntities();
CommonCodesEntities ccContext = new CommonCodesEntities();
for (int i = 0; i <= 20; i++)
{
var allocations = (from a in invContext.vAllocations
where a.AuditGroupId == 9107
select a).AsEnumerable();
var q = from a in allocations
join c in ccContext.vContainerEntity on a.ContainerId equals c.ContainerId
select new
{
ContainerNo = a.ContainerNo,
PortATD = c.ATD,
ATA_KL = a.ServiceDate,
RateWithoutVat = a.RateWithoutVat,
OrderTypeId = c.OrderTypeId,
DestinationCityId = c.DestinationCityId,
Quantity = 1
};
var result = q.ToList();
Console.WriteLine(result.Where(x=>x.DestinationCityId == 14).ToList().Count);
}
Resulting console output
64
62
58
58
64
62
60
60
56
60
62
60
58
54
56
64
58
Very strange :D
I have the following data in a SQL Table:
I want to find 3 Consecutive data by No and group with ID. Result are
How to write query.please help.
Here is query which select only rows where actually 3 consecutive rows are:
SELECT a.*
FROM
TABLE as a
inner join
TABLE as b on (a.no+1=b.no and a.id=b.id)
inner join
TABLE as c on (a.no+2=c.no and a.id=c.id)
order by a.id, a.no
for your data it will provide:
4 a1 4
5 a1 3
1 a2 2
2 a2 4
3 a3 2
4 a3 3
rows (6,a1,1), (3,a2,5) and (5,a3,4) are not selected, as there are no (8,a1) (5,a2) and (7,a3)
DECLARE #temp TABLE (NO int,ID VARCHAR(2),QTY int)
INSERT INTO #temp
SELECT 1,'A1',5 UNION ALL
SELECT 4,'A1',4 UNION ALL
SELECT 5,'A1',3 UNION ALL
SELECT 6,'A1',1 UNION ALL
SELECT 7,'A1',0 UNION ALL
SELECT 9,'A1',5 UNION ALL
SELECT 12,'A1',3 UNION ALL
SELECT 1,'A2',2 UNION ALL
SELECT 2,'A2',4 UNION ALL
SELECT 3,'A2',5 UNION ALL
SELECT 4,'A2',1 UNION ALL
SELECT 7,'A2',4 UNION ALL
SELECT 9,'A2',5 UNION ALL
SELECT 1,'A3',0 UNION ALL
SELECT 3,'A3',2 UNION ALL
SELECT 4,'A3',3 UNION ALL
SELECT 5,'A3',4 UNION ALL
SELECT 6,'A3',2;
WITH tmpa AS
(
SELECT *
, NO - ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS grp
FROM #temp
)
, tmpb AS
(
SELECT *
, COUNT(*) OVER(PARTITION BY ID,grp) AS grpcount
FROM tmpa
)
SELECT NO,ID,QTY FROM tmpb WHERE grpcount>1;
Result are
4 A1 4
5 A1 3
6 A1 1
7 A1 0
1 A2 2
2 A2 4
3 A2 5
4 A2 1
3 A3 2
4 A3 3
5 A3 4
6 A3 2
I found this query from this link.
Find ānā consecutive free numbers from table
http://sqlfiddle.com/#!1/a2633/2
Answer Credit by
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have Process SQL Server table and some columns and their values.
ID Step StateID SenderNo
61cc2608-81b8-48a2-89ce-8887438985bb 9 125 1750069133
61cc2608-81b8-48a2-89ce-8887438985bb 8 120 1111111162
61cc2608-81b8-48a2-89ce-8887438985bb 5 116 1111111162
61cc2608-81b8-48a2-89ce-8887438985bb 2 115 3900383669
61cc2608-81b8-48a2-89ce-8887438985bb 1 113 1750069133
14dsfgd4-123d-21ds-86ds-124sgslkgj31 9 125 1750069133
14dsfgd4-123d-21ds-86ds-124sgslkgj31 8 120 1111111162
14dsfgd4-123d-21ds-86ds-124sgslkgj31 5 116 1111111162
14dsfgd4-123d-21ds-86ds-124sgslkgj31 2 115 3900383669
14dsfgd4-123d-21ds-86ds-124sgslkgj31 1 113 1750069133
21456qwf-674s-75df-53sg-125sdfsgsd47 5 116 1111111162
21456qwf-674s-75df-53sg-125sdfsgsd47 2 115 3900383669
21456qwf-674s-75df-53sg-125sdfsgsd47 1 113 1750069133
I want to get data according to highest Step value. Like that;
ID Step StateID SenderNo
61cc2608-81b8-48a2-89ce-8887438985bb 9 125 1750069133
14dsfgd4-123d-21ds-86ds-124sgslkgj31 9 125 1750069133
21456qwf-674s-75df-53sg-125sdfsgsd47 5 116 1111111162
I have no idea how to write the necessary T-SQL query in ASP.Net (C#)...
The first thing to do is to write the TSQL that you need. By my reckoning, that is:
select ID, Step, StateID, SenderNo
from (
select *, row_number() over(partition by ID order by Step desc) as [_row]
from Process) x where x.[_row]=1
Next, you need to talk to the server in code. I'm going to use "dapper" for convenience:
using(var conn = new SqlConnection(ConnectionString))
{
var rows = conn.Query<Process>(#"
select ID, Step, StateID, SenderNo
from (
select *, row_number() over(partition by ID order by Step desc) as [_row]
from Process) x where x.[_row]=1").ToList();
// ... use rows
}
where Process is a class you define with suitable ID, Step, StateID, SenderNo properties. Or you can avoid that via dynamic:
using(var conn = new SqlConnection(ConnectionString))
{
var rows = conn.Query(#"
select ID, Step, StateID, SenderNo
from (
select *, row_number() over(partition by ID order by Step desc) as [_row]
from Process) x where x.[_row]=1").ToList();
foreach(var row in rows)
{
Console.WriteLine(row.ID); // dynamic member resolution
Console.WriteLine(row.Step);
//...
}
}
There are lots of examples on the web showing how to query a database in ASP.NET but the query you want would be along the lines of
SELECT *
FROM (
SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY id ORDER BY step DESC)
FROM tbl
) t
WHERE rn=1