Linq联盟用法?

SQL:

SELECT date,total_usage_T1 as TotalUsageValue,'T1' as UsageType FROM TblSayacOkumalari UNION ALL SELECT date,total_usage_T2 as TotalUsageValue,'T2' as UsageType FROM TblSayacOkumalari 

我尝试将其转换为linq

 IEnumerable sayac_okumalari = entity.TblSayacOkumalari .Select(x => new { x.date, x.total_usage_T1 }) .Union(entity.TblSayacOkumalari.Select(x => new { x.date, x.total_usage_T2 })); 

但我不知道如何将'T1' as UsageType转换'T1' as UsageType转换为linq。 我的工会使用也是不正确的。

我的表字段如下:

 | date | total_usage_T1 | total_usage_T2 | | 2010 | 30 | 40 | | 2011 | 40 | 45 | | 2012 | 35 | 50 | 

我想这样

 | date | TotalUsageValue | UsageType | | 2010 | 30 | T1 | | 2011 | 40 | T1 | | 2012 | 35 | T1 | | 2010 | 40 | T2 | | 2011 | 45 | T2 | | 2012 | 50 | T2 | 

我努力了,但不能。 请帮忙。

编辑

 Def. from MSDN Enumerable.Concat - Concatenates two sequences. Enumerable.Union - Produces the set union of two sequences by using the default equality comparer. 

我的post: Concat()vs Union()

  IEnumerable sayac_okumalari = entity.TblSayacOkumalari .Select(x => new { date= x.date, TotalUsageValue = x.total_usage_T1, UsageType = "T1" }) .Concat(entity.TblSayacOkumalari .Select(x => new { date= x.date, TotalUsageValue = x.total_usage_T2, UsageType = "T2" } )); 

对于使用类型,您需要在新的匿名类型中添加UsageType = "T2" ,因为我在上面执行此操作将为您完成任务


比你应该去Concat方法而不是Union方法..

  int[] ints1 = { 1, 2, 3 }; int[] ints2 = { 3, 4, 5 }; IEnumerable union = ints1.Union(ints2); Console.WriteLine("Union"); foreach (int num in union) { Console.Write("{0} ", num); } Console.WriteLine(); IEnumerable concat = ints1.Concat(ints2); Console.WriteLine("Concat"); foreach (int num in concat) { Console.Write("{0} ", num); } 

产量

在此处输入图像描述

关于Union和Concat的事实

输出显示Concat()方法只将两个可枚举集合合并为单个集合但不执行任何操作/过程任何元素只返回具有两个可枚举集合的所有元素的单个可枚举集合。

Union()方法通过消除重复返回可枚举集合,即如果在执行union的两个可枚举集合中存在相同元素,则返回单个元素。

注意要点

  • 通过这个事实,我们可以说Concat()比Union()更快,因为它不进行任何处理。

  • 但是如果在使用具有单个集合的Concat()和具有过多重复元素的数量之后组合两个集合并且如果要对该创建的集合执行进一步操作比使用Union()方法创建的集合花费更长的时间,因为Union()消除了重复并使用较少的元素创建集合。

用这个:

 var result = entity.TblSayacOkumalari .Select(x => new { Date = x.date, TotalUsage = x.total_usage_T1, UsageType = "T1" }) .Union(entity.TblSayacOkumalari.Select(x => new { Date = x.date, TotalUsage = x.total_usage_T2, UsageType = "T2" })); 

为了获得匿名类型的预期属性名称,您可能希望执行以下操作:

 new { x.date, TotalUsage = x.total_usage_T1, UsageType="T1" } 

并且

 new { x.date, TotalUsage = x.total_usage_T2, UsageType="T2" }