Frage

Ich habe Table1 und Table2 in der Form IEnumerable<DataRow>.Beide Tabellen haben Spalten Column1 Und Column2.

Ich würde gerne einen Left Outer Join machen Column1 und möchte die Anzahl der vorhandenen Zeilen erhalten Table2 und laden Sie die Datensätze in eine DataTable.

Ich habe die folgende Abfrage versucht

var query = from p in Table1
            join q in Table2 on p.Field<string>("Column1") equals q.Field<string>("Column1") into pq
            from xyz in pq.DefaultIfEmpty()
            group xyz by new { Col1 = p.Field<string>("Column1"), Col2 = p.Field<string>("Column2") } into g
            select dtFinalData.LoadDataRow(new object[]
            {
                g.Key.Col1,
                g.Key.Col2,                               
                g.Count
            }, false);

Da „g“ die gruppierten Daten darstellt, gibt g.count 1 für Zeilen zurück, die keine Einträge in Tabelle 2 haben.Ich möchte für diese Zeilen „0“ zurückgeben.

Eingabe:

Tabelle 1

Col1Val1       Col2Val1

Col1Val2       Col2Val2

Tabelle 2

Col1Val1       Col2Val1

Col1Val1       Col2Val1

Aktueller Output :

Col1Val1        Col2Val1    2

Col2Val2        Col2Val2    1

Erwartete Ergebnisse :

Col1Val1        Col2Val1    2

Col2Val2        Col2Val2    0

Ich habe es mir angeschaut LINQ – Left Join, Group By und Count aber ich konnte das Gleiche nicht auf meine Anfrage anwenden ...

Können Sie mir helfen, diese Frage zu beheben?

War es hilfreich?

Lösung

let es sei so:

from p in Table1
let p1 = p.Field<string>("Column1")
let p2 = p.Field<string>("Column2") 
let qs = 
  from q in Table2
  where p1 == q.Field<string>("Column1")
  select q
let qCount = qs.Count()
select dtFinalData.LoadDataRow(new object[]
{
  p1,
  p2,
  qCount
}, false);

Da ich nicht beigetreten bin, muss ich keine Gruppe bilden.Jede Ergebniszeile entspricht einer Zeile in Tabelle1.


Hier ist eine GroupJoin-Lösung:

from p in Table1 
let pkey = new { c1 = p.Field<string>("Column1"), c2 = p.Field<string>("Column2") }
join q in Table2 on pkey equals
  new { c1 = q.Field<string>("Column1"), c2 = q.Field<string>("Column2") }
  into qs
select dtFinalData.LoadDataRow(new object[] 
{ 
  pkey.c1, 
  pkey.c2, 
  qs.Count() 
}, false); 

Und hier ist eine Join-and-Group-Lösung.

from p in Table1 
let pkey = new { c1 = p.Field<string>("Column1"), c2 = p.Field<string>("Column2") }
join q in Table2 on pkey equals
  new { c1 = q.Field<string>("Column1"), c2 = q.Field<string>("Column2") }
  into right
from q in right.DefaultIfEmpty()
group q by pkey into g
select dtFinalData.LoadDataRow(new object[] 
{ 
  g.Key.c1, 
  g.Key.c2, 
  g.Count(q => q != null) 
}, false); 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top