0

我有数据集,其中包含两个这样的表:

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");

DataSet ds = new DataSet("tmpFieldSet");

ds.Tables.Add(dtFields);
ds.Tables.Add(dtCDGroup);

如何将以下 SQL 查询写入 LINQ

queryString = "Select FieldID, tmpCDGroup.Name, CDCaption, IIF(ISNULL(Priority),99,Priority), fldIndex from tmpFieldList LEFT OUTER JOIN tmpCDGroup ON tmpFieldList.CDGroupID = tmpCDGroup.CDGroupID order by 4,5 ";
4

2 回答 2

1

我不确定您为什么要按“4,5”订购,但它会是这样的:

var resultArray = tmpFieldList.Join(
    tmpCDGroup,                           // inner join collection
    fieldList => fieldList.CDGroupID,     // outer key selector
    cd => cd.CDGroupID,                   // inner key selector
    (fieldList, cd) => new {             // result selector
        FieldID = fieldList.FieldID, 
        Name = cd.Name, 
        CDCaption = cd.CDCaption, 
        Priority = fieldList.Priority ?? 99, 
        fldIndex = fieldList.fldIndex
     })
.OrderBy(result => result.Priority)
.ThenBy(result => result.fldIndex)
.ToArray();

然后您可以访问使用,例如,

resultArray[0].FieldID

, ETC。

于 2012-04-17T07:32:41.713 回答
0

这可能会起作用,或者至少有助于使其正常工作。请注意,我已经更改了某些列的类型。

var result = from field in dtFields.AsEnumerable()
             join cdGroup in dtCDGroup.AsEnumerable()
             on field.Field<int>("CDGroupID") equals cdGroup.Field<int>("CDGroupID") 
                    into fieldGroup
             from row in fieldGroup.DefaultIfEmpty()
             let priority = row.IsNull("Priority") ? 99 : row.Field<int>("Priority")
             orderby priority, row.Field<int>("fldIndex")
             select new
             {
                 FieldID   = row.Field<int>("FieldID"),
                 GroupName = row.Field<int>("Name"),
                 CDCaption = row.Field<int>("CDCaption"),
                 Priority  = priority,
                 fldIndex  = row.Field<int>("fldIndex")
             };
于 2012-04-17T07:57:04.607 回答