Linq查询c#中的数据集?

时间:2012-04-17 07:20:22

标签: c# linq c#-4.0 linq-to-dataset

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

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

2 个答案:

答案 0 :(得分: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

等。

答案 1 :(得分: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")
             };