linq中两个数据表之间的左外连接

时间:2014-05-05 06:44:26

标签: c# .net linq left-join

我有两张桌子:

id | code      code | name
----------    -------------
1  | 001       001  | first
2  | 002       002  | second
3  | 001

结果必须是

id | name
----------
1  | fisrt
2  | second
3  | first

我的linq查询:

var query = from content in result.Tables["Special_Contents_Tree"].AsEnumerable()
            join iNames in result.Tables["Special_Contents_ItemNames"].AsEnumerable()
            on content.Field<Nullable<Int16>>("Code") equals iNames.Field<Nullable<Int16>>("Code") into outer
            from gr in outer.DefaultIfEmpty()
            select new
            {
              ID = (Int16)content["ID"],
              Name = gr["Name"]
            };

DataTable SpecialContent = new DataTable();
SpecialContent.Columns.Add("ID");
SpecialContent.Columns.Add("Name");
foreach (var q in query)
{
   SpecialContent.Rows.Add(q.ID, q.Name);
}

但结果有误 - result.Tables["Special_Contents_Tree"].Rows.Count = 323然后SpecialContent.Rows.Count应该是323,SpecialContent.Rows.Count = 484

0 个答案:

没有答案