LINQ to SQL分组到空白数据行?

时间:2018-10-10 05:10:43

标签: c# sql linq

我在sql中有以下代码:

SELECT "Field 1" AS fullname, null  AS limsuser_id
   UNION 
SELECT fullname, limsuser_id from table1
   UNION
SELECT "Field 2" AS fullname, null  AS limsuser_id
   UNION 
SELECT fullname, limsuser_id from table2

基本上,“字段1”和“字段2”充当标题。
现在,这将返回ASP.net端的数据集。

但是,当有人在对数据集进行排序时单击“全名”时,数据也将同时使用“字段1”和“字段2”进行排序。

排序前:

Field 1
Jason Z   | 25
Anthony P | 21

Field 2
Shane | 24
Damon | 23

排序后:

Anthony P | 21
Damon     | 23
Field 1
Field 2
Jason Z   | 25
Shane     | 24

预期结果:

Field 1
Anthony P | 21
Jason Z   | 25
Field 2
Damon | 23
Shane | 24

如何使用linq对具有“字段1”和“字段2”的数据集进行分组? 这是一个简化的sql。我没有更改SQL查询的自由。

2 个答案:

答案 0 :(得分:1)

您应该有一个字段,显示您从哪个表中获取了它们:

SELECT "Field 1" AS fullname, null  AS limsuser_id, 1 as [order]
   UNION 
SELECT fullname, limsuser_id, 1 as [order] from table1 
   UNION
SELECT "Field 2" AS fullname, null  AS limsuser_id, 2 as [order]
   UNION 
SELECT fullname, limsuser_id, 2 as [order] from table2

然后您可以简单地执行以下操作:

var result = yourItems.OrderByDescending(x=> x.fullname == "Field 1" || x.fullname == "Field 2")
    .ThenBy(x=> x.fullname)
    .GroupBy(x=> x.order);

.OrderByDescending(x=> x.fullname == "Field 1" || x.fullname == "Field 2")确保Field 1Field 2无论他们的无序顺序如何,都将站在他们的团队之首。

.ThenBy(x=> x.fullname)然后将其按fullname

进行排序

然后您可以在order字段中按组分组。

或者如果仅Field 1Field 2的ID为空,则可以执行以下操作:

var result = yourItems.OrderByDescending(x=> x.limsuser_id  == null)
    .ThenBy(x=> x.fullname)
    .GroupBy(x=> x.order);

答案 1 :(得分:1)

@Ashkan建议的新方法将起作用。但是根据您的要求,您可能不需要分组。只需添加一列即可为4组中的每组标识具有不同值的订单

SELECT "Field 1" AS fullname, null  AS limsuser_id, 1 AS order_no
   UNION 
SELECT fullname, limsuser_id, 2 AS order_no from table1 
   UNION
SELECT "Field 2" AS fullname, null  AS limsuser_id, 3 AS order_no
   UNION 
SELECT fullname, limsuser_id, 4 AS order_no from table2

然后在Linq中订购

var orderedSet = items.OrderBy(x=> x.order_no).ThenBy(x=> x.fullname);