Question

I have a SQL database that I'm using LINQ to connect to (LINQ To SQL) and a local set of XML data (in a dataset). I need to perform an outer left join on the SQL table "tblDoc" and dataset table "document" on the keys "tblDoc:sourcePath, document:xmlLink". Both keys are unfortunately strings. The code I have below doesn't return any results and I've tried a few variations but my LINQ skills are limited. Does anyone have any suggestions or alternate methods to try?

DataColumn xmlLinkColumn = new DataColumn(
    "xmlLink",System.Type.GetType("System.String"));
xmlDataSet.Tables["document"].Columns.Add(xmlLinkColumn);
foreach (DataRow xmlRow in xmlDataSet.Tables["document"].Rows)
{
    xmlRow["xmlLink"] = (string)xmlRow["exportPath"] + 
        (string) xmlRow["exportFileName"];            
}

var query =
    from t in lawDataContext.tblDocs.ToList()
    join x in xmlDataSet.Tables["Document"].AsEnumerable()
    on t.SourceFile equals (x.Field<string>("xmlLink"))
    select new
    {
        lawID = t.ID,
        xmlID = x == null ? 0 : x.Field<int>("id")
    };       

foreach (var d in query.ToArray())
{
    Debug.WriteLine(d.lawID.ToString() + ", " + d.xmlID.ToString());
}
Was it helpful?

Solution

The join clause produces standard inner join behavior. To get an outer join, you need to use the DefaultIfEmpty() extension method:

var query = from t in lawDataContext.tblDocs.ToList()
            join x in xmlDataSet.Tables["Document"].AsEnumerable()
                on t.SourceFile equals (x.Field<string>("xmlLink"))
                into outer
            from o in outer.DefaultIfEmpty()
            select new
            {
                lawID = t.ID,
                xmlID = o == null ? 0 : o.Field<int>("id")
            }; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top