将T-SQL(distinct,group by,union)转换为LINQ

时间:2013-12-18 02:08:28

标签: c# sql linq

我熟悉t-sql但不熟悉LINQ,我曾尝试过基本的linq但不确定这个。 我不确定下面我写的sql语句中是否有linq中的确切等价物。 基本上我想将linq结果传递给我的域模型。

sql查询使用相同的视图(1 sql视图)

域名模型

Public class Result
{
 Public int Key{get;set;}
 Public string Name{get;set;}
}

SQL查询

SELECT DISTINCT Name = Field1 ,ItemKey = Field2 FROM sql_view
UNION 
SELECT DISTINCT Name = Field3 ,ItemKey = Field4 FROM sql_view 
UNION 
SELECT DISTINCT Name = Field5 ,ItemKey = Field6 FROM sql_view 
UNION 
SELECT  Name = Field7 ,ItemKey = Field8 FROM sql_view

sql_vw的示例数据

Field1 Field2 Field3 Field4 Field5 Field6 Field7 Field8
1      A1     23     FF23     322  ZZ322     10  A10   
1      A1     23     FF23     322  ZZ322     21  R21
1      A1     23     FF23     322  ZZ322     31  E31
2      B2     22     PP22     331  WW331     3   A3   
2      B2     22     PP22     331  WW331     7   R7
2      B2     22     PP22     331  WW331     9   E9
2      B2     22     PP22     331  WW331     12  E12
3      C3     26     HH26     340  NN340     43  H43
3      C3     26     HH26     340  NN340     39  J39

2 个答案:

答案 0 :(得分:0)

(from v in context.View
group v by new {v.Field1, v.Field2} into g
select new Result{Key = g.Key.Field1, Item = g.Key.Field2})
.Union()//more of this may be

更新了分组

答案 1 :(得分:0)

为了让事情更容易阅读和理解,我会做那样的事情

var part1 = context.View.Select(m => new {Name = m.Field1, ItemKey = m.Field2});
var part2 = context.View.Select(m => new {Name = m.Field3, ItemKey = m.Field4});
var part3 = context.View.Select(m => new {Name = m.Field5, ItemKey = m.Field6});
var part4 = context.View.Select(m => new {Name = m.Field7, ItemKey = m.Field8});

var result = (part1.Union(part2).Union(part3).Union(part4)).Distinct();