V.Hunon
V.Hunon

Reputation: 320

C# LINQ left join 2 Datatables

I have 2 Datatables, they should join on "UserID" but it doesn't work. I've read the docs and other solutions but they wont work either.

var dtjoined = from DataFileInfos in FileInfo.AsEnumerable()
                       join Recips in dtMail.AsEnumerable()
                       on DataFileInfos["UserID"] equals Recips["User name"]
                       into Tb3
                       from Tb3row in Tb3.DefaultIfEmpty()
                       select Tb3;

I want at the end a datatable with a left join. I don't get the gist of LINQ, even reading the docs, can someone explain me that?

And how do I get the datatable? I would do something like

foreach(var enum in dtjoined)
{
//do something to add that
myDatatable.rows.add(enum);
}

EDIT: FileInfo:

Datatable FileInfo = new Datatable();
FileInfo.Columns.Add("Anything",typeof(anything));
...
FileInfo.Columns.Add("UserID",typeof(string));

dtMail:

Datatable dtMail= new Datatable();
    dtMail.Columns.Add("Anything",typeof(anything));
    ...
    dtMail.Columns.Add("User name",typeof(string));

These were my two tables and I want them to join on UserID So at the end I got the following result:

[FileInfo Column1] [FileInfo Column2] [FileInfo Column3] [FileInfo UserID] [dtMail E-Mail]
SomeValue            SomeValue             SomeValue          UserID1          SomeMail

Upvotes: 0

Views: 542

Answers (1)

Anmol Rathod
Anmol Rathod

Reputation: 159

try this below code and in below i just used some class just to show you how we can return a custom object using LinQ.

var dtjoined = from DataFileInfos in FileInfo.AsEnumerable()
                   join Recips in dtMail.AsEnumerable()
                   on DataFileInfos.Field<string>("UserID") equals Recips.Field<string>("User name") 
                   select new { FirstColumn= DataFileInfos.FirstColumn, ... }; // or select new { FirstColumn= DataFileInfos.FirstColumn, ... }.ToList();

this will return an object and incase you want a list than select DataFileInfos or Recips object or you can also go for creating another object which holds a list.

Upvotes: 0

Related Questions