0

我有两个DataTable

DataTable dtFields = new DataTable("tmpFieldTable");                
dtFields.Columns.Add("FieldID");
dtFields.Columns.Add("CDGroupID");
dtFields.Columns.Add("CDCaption");
dtFields.Columns.Add("fldIndex");

DataTable dtCDGroup = new DataTable("tmpCDGroup");               
dtCDGroup.Columns.Add("CDGroupID");
dtCDGroup.Columns.Add("Name");
dtCDGroup.Columns.Add("Priority");

我正在使用以下 LINQ 表达式来加入这些表:

var resultList = dtFields.AsEnumerable()
                         .Join(dtCDGroup.AsEnumerable(),
                               fieldList => fieldList.Field<string>("CDGroupID"),
                               cd => cd.Field<string>("CDGroupID"),
                               (fieldList, cd) => new
                               {
                                   FieldID = fieldList.Field<string>("FieldID"),
                                   CdGroup = cd.Field<string>("Name"),
                                   CDCaption = fieldList.Field<string>("CDCaption"),
                                   Priority = (cd.Field<string>("Priority") ?? "99"),
                                   fldIndex = fieldList.Field<string>("fldIndex").ToString()
                               })
                         .OrderBy(result => result.Priority)
                         .ThenBy(result => result.fldIndex);

如何使用这些DataTables 执行左外连接?

4

2 回答 2

0

只需添加DefaultIfEmpty()到您的表中:

resultList = dtFields.AsEnumerable() 
                     .Join(dtCDGroup.AsEnumerable().DefaultIfEmpty(), 
                           fieldList => fieldList.Field<string>("CDGroupID"), 
                           cd => cd.Field<string>("CDGroupID"), 
                           (fieldList, cd) => new 
                           { 
                               FieldID = fieldList.Field<string>("FieldID"), 
                               CdGroup = cd.Field<string>("Name"), 
                               CDCaption = fieldList.Field<string>("CDCaption"), 
                               Priority = (cd.Field<string>("Priority") ?? "99"), 
                               fldIndex = fieldList.Field<string>("fldIndex").ToString() 
                           }) 
                     .OrderBy(result => result.Priority) 
                     .ThenBy(result => result.fldIndex);
于 2012-04-18T09:15:12.377 回答
0

使用 lambda 表达式本机不提供左连接。但是您可以使用 GroupJoin 和 SelectMany 方法来实现这一点。

var result = new string[] { "A", "B" }.GroupJoin(new string[] { "B" }, l => l, r => r, (l, r) => new { l, r }).ToList();
            Console.WriteLine(result.Count());

这将导致 result[0].r.Count() = 0 和 result[1].r.Count() = 1。

希望这会有所帮助。

问候。

于 2012-04-18T05:17:48.500 回答