如何在linq查询中保持表的准确顺序

本文关键字:顺序 linq 查询 | 更新日期: 2023-09-27 18:02:51

我有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();

但是在上面的查询中,我得到的输出低于我在第2位获得Sub3,但在我的SubvariantCodes表中,Sub3位于第3位

Division: Sub1,Sub3,Sub2, Sub4

在linq查询中可以这样做吗??

如何在linq查询中保持表的准确顺序

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

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方法文档- 备注部分:

中提到。

Join<TOuter,> 保留outer中元素的顺序,对于这些元素中的每一个,保留inner

中匹配元素的顺序。