我有两个DataTable
s:
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);
如何使用这些DataTable
s执行左外连接?
答案 0 :(得分: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());
这将导致结果[0] .r.Count()= 0并且结果[1] .r.Count()= 1。
希望这会有所帮助。
问候。
答案 1 :(得分: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);