[英]Using Row_Number of SQL Server in Linq
I have a table with data like 我有一个数据表
Date Users
------------------
01/03/2015 25
02/03/2015 28
04/03/2015 36
07/03/2015 45
08/03/2015 47
I had created a table valued function in Sql Server using Row_Number which gave me output like below which I used for further processing 我已经使用Row_Number在Sql Server中创建了一个表值函数,该函数给了我类似下面的输出,用于进一步处理
Date Users UsersAdded
----------------------------------
01/03/2015 25 0
02/03/2015 28 3
04/03/2015 36 8
07/03/2015 45 9
08/03/2015 47 2
However, I need to do the same thing in Linq now but it does not has the Row_Number function. 但是,我现在需要在Linq中做同样的事情,但是它没有Row_Number函数。 I had a look at How do I translate a query that uses ROW_NUMBER() into linq?
我看看如何将使用ROW_NUMBER()的查询转换为linq? but that is not related to my query.
但这与我的查询无关。
My query in SQL had Rownum upon the date field and query was 我在SQL查询中在日期字段上有Rownum,查询是
select date, Users, (T1.Users - isnull(T2.Users,0)) as UsersAdded
from tableuser T1
join tableuser T2 on T1.Rownum = (T2.RowNum +1)
I am new to LINQ so don't even know how to start on this query. 我是LINQ的新手,所以甚至不知道如何开始此查询。 Any help would be appreciated.
任何帮助,将不胜感激。
Use the date column to find the next lowest date by dong a left outer join using from
/ where
. 使用日期栏里找到董下一最低日期使用左外连接
from
/ where
。
var ans = from t1 in tableuser from t2 in tableuser.Where(t2 => t2.Date == tableuser.Where(t3 => t3.Date < t1.Date).Max(t3 => t3?.Date)).DefaultIfEmpty()
select new { t1.Date, t1.Users, UsersAdded = t1.Users - (t2?.Users ?? t1.Users)};
PS I think your example query may have an issue with the first answer row? PS我认为您的示例查询可能与第一个答案行有问题?
Use LINQ to object. 使用LINQ进行反对。 Refer the link https://msdn.microsoft.com/en-us/library/bb534869.aspx
请参阅链接https://msdn.microsoft.com/en-us/library/bb534869.aspx
It will be achieved like this 这样会实现
string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; var query = fruits.Select((fruit, index) => new { index, str = fruit.Substring(0, index) }); foreach (var obj in query) { Console.WriteLine("{0}", obj); } /* This code produces the following output: {index=0, str=} {index=1, str=b} {index=2, str=ma} {index=3, str=ora} {index=4, str=pass} {index=5, str=grape} */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.