LINQ to SQL group由一行空白数据组成?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LINQ to SQL group由一行空白数据组成?相关的知识,希望对你有一定的参考价值。
我在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
基本上,“Field 1”和“Field 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在“Field 1”和“Field 2”的数据集上进行分组?这是一个简化的SQL。我没有自由改变sql查询。
您应该有一个字段显示您从哪个表中获取它们:
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 1
和Field 2
将站在他们的团体之上,无论他们的aphabetical命令是什么。
然后.ThenBy(x=> x.fullname)
将由fullname
对其进行排序
然后你可以在order
字段上进行GroupBy。
或者如果你只有Field 1
和Field 2
的空id,你可以这样做:
var result = yourItems.OrderByDescending(x=> x.limsuser_id == null)
.ThenBy(x=> x.fullname)
.GroupBy(x=> x.order);
@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);
以上是关于LINQ to SQL group由一行空白数据组成?的主要内容,如果未能解决你的问题,请参考以下文章
Linq to SQL -- Group ByHaving和ExistsInAnyAllContains
LINQ体验——LINQ to SQL语句之Group By/Having和Exists/In/Any/All/Contains