如何在linq查询中使用表的确切顺序维护记录顺序?

时间:2016-08-17 15:00:20

标签: c# .net linq datatable

我正在2 datatables with following records in dataset

SubvariantCodes:

Code              Desc
Sub1              Subvariant1
Sub2              Subvariant2
Sub3              Subvariant3
Sub4              Subvariant4

dtVariant:

Name        Type        status
Variant1    Division    active
Variant2    Division    active
Variant3    Division    active

dtSubVariant:

Name        Type             Code 
Variant1    Division         Sub1
Variant1    Division         Sub3
Variant2    Division         Sub1
Variant2    Division         Sub2
Variant2    Division         Sub3
Variant2    Division         Sub4
Variant3    Division         Sub1
Variant3    Division         Sub2

现在我想获得Subvariant codes unique list type wise for only those variant whose status is active with the same ordering of those Subvariant codes as they are in SubvariantCodes datatable.

预期输出:

Division: Sub1,Sub2,Sub3,Sub4

代码

var data = (from master in Ds1.Tables["dtVariant"].Rows.Cast<DataRow>()
                     join child in Ds1.Tables["dtSubVariant"].Rows.Cast<DataRow>()
                     on new 
                     { 
                         X1 = master.Field<string>("Name"),
                         X2 = master.Field<string>("Type"), 
                         X3 = master.Field<string>("Code")
                     }
                     equals new 
                     {
                         X1 = child.Field<string>("Name"),
                         X2 = child.Field<string>("Type"),
                         X3 = child.Field<string>("Code")
                     }
                     where master.Field<string>("status") == "active"
                     group child by child.Field<string>("Type") into cms
                     select new
                     {
                         names = (from dp in cms
                                  join subvariantcode in Ds1.Tables["SubvariantCodes"].AsEnumerable()
                                  on dp.Field<string>("Code") equals subvariantcode.Field<string>("Code")
                                  select new
                                  {
                                      Names = subvariantcode.Field<string>("Code".ToLower()),
                                  }).Distinct().ToList()
                     }).ToList();

但是在上面的查询中我得到的输出低于我在第二个位置获得 Sub3但在我的SubvariantCodes表中sub3在第三个位置

Division: Sub1,Sub3,Sub2, Sub4

这可以在linq查询中执行吗???

1 个答案:

答案 0 :(得分:2)

为了实现您的目标,在此连接中交换外部和内部序列就足够了:

names = (from dp in cms
         join subvariantcode in Ds1.Tables["SubvariantCodes"].AsEnumerable()
         on dp.Field<string>("Code") equals subvariantcode.Field<string>("Code")
像这样:

names = (from subvariantcode in Ds1.Tables["SubvariantCodes"].AsEnumerable()
         join dp in cms
         on subvariantcode.Field<string>("Code") equals dp.Field<string>("Code")

Join方法文档中提到了此行为 - 备注部分:

  

加入&LT; TOuter,TINNER,TKEY的,TResult&GT; 保留外部元素的顺序,并为每个元素保留内部匹配元素的顺序。