Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c# - LEFT OUTER JOIN 2 datatables

I'm trying to understand how to query, preferably with LINQ, 2 datatables. I would like to do a LEFT OUTER JOIN on them

Datatable1 with col's: [ID] [colA]
DataTable2 with col's: [ID] [ColB] [ColC] ...

Looking to join on that ID.

Can someone please show me an example so I can apply it to the datatables I have? Thank you in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This compiles and does what you would expect based on the result set given:

// create the default row to be used when no value found
var defaultRow = DataTable2.NewRow();
defaultRow[0] = 0;
defaultRow[1] = String.Empty;

// the query
var result = from x in DataTable1.AsEnumerable()
    join y in DataTable2.AsEnumerable() on (string)x["ID"] equals (string)y["ID"] 
             into DataGroup
    from row in DataGroup.DefaultIfEmpty<DataRow>(defaultRow)
    select new {a = x["ColA"], b = (string)row["ColB"]};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...