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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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"]};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...