Ali*_*hşi 8 c# sql linq sql-to-linq-conversion
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
Run Code Online (Sandbox Code Playgroud)
我尝试将其转换为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 }));
Run Code Online (Sandbox Code Playgroud)
但我不知道如何转换'T1' as UsageType为linq.我的工会使用也是不正确的.
我的表字段如下:
| date | total_usage_T1 | total_usage_T2 |
| 2010 | 30 | 40 |
| 2011 | 40 | 45 |
| 2012 | 35 | 50 |
Run Code Online (Sandbox Code Playgroud)
我想要这样
| date | TotalUsageValue | UsageType |
| 2010 | 30 | T1 |
| 2011 | 40 | T1 |
| 2012 | 35 | T1 |
| 2010 | 40 | T2 |
| 2011 | 45 | T2 |
| 2012 | 50 | T2 |
Run Code Online (Sandbox Code Playgroud)
我努力了,但不能.请帮忙.
Pra*_*ana 17
编辑
Def. from MSDN
Enumerable.Concat - Concatenates two sequences.
Enumerable.Union - Produces the set union of two sequences by using the default equality comparer.
Run Code Online (Sandbox Code Playgroud)
我的帖子:Concat()vs Union()
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" }
));
Run Code Online (Sandbox Code Playgroud)
对于使用类型,你需要添加UsageType = "T2"新的匿名类型,就像我上面所做的那样,这将为你完成任务
比你应该去Concat方法而不是Union方法..
例
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);
}
Run Code Online (Sandbox Code Playgroud)
产量

关于Union和Concat的事实
输出显示Concat()方法只将两个可枚举集合组合到单个集合中,但不执行任何操作/处理任何元素只返回具有两个可枚举集合的所有元素的单个可枚举集合.
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"
}));
Run Code Online (Sandbox Code Playgroud)