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<TblSayacOkumalari> 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
到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.
我的帖子: CONCAT()VS联盟()
IEnumerable<TblSayacOkumalari> 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" }
));
对于使用类型,你JUSE需要添加UsageType = "T2"
在新的匿名类型,因为我做了上面这将做任务给你
比你应该去的毗连方法,而不是联盟的方法..
例
int[] ints1 = { 1, 2, 3 }; int[] ints2 = { 3, 4, 5 };
IEnumerable<INT> union = ints1.Union(ints2);
Console.WriteLine("Union");
foreach (int num in union)
{
Console.Write("{0} ", num);
}
Console.WriteLine();
IEnumerable<INT> concat = ints1.Concat(ints2);
Console.WriteLine("Concat");
foreach (int num in concat)
{
Console.Write("{0} ", num);
}
产量
其实关于联盟的毗连
输出显示的毗连()方法只是将两个枚举集合到单一,但不执行任何操作/过程中的任何元素只是两个枚举集合所有元素返回一个枚举集合。
联盟()方法,通过消除重复的,即只返回一个元素,如果在其上进行联合两个枚举集合中存在相同的元素返回枚举集合。
重要的一点要注意:
用这个:
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" }