i don't know why i get different results between this SQL and LINQ
Could you like to tell me why...?
SQL:
select distinct top 50 (id) as d_id
from talbe1
where id<>-1
order by d_id asc;
Linq:
IList<int> myResults =
(from t in dbconn.table1
where t.id != -1
orderby t.id ascending
select t.id
).Distinct().Take(50).ToList();
int callCnt = 0;
foreach (int row in myResults)
{
callCnt++;
Console.WriteLine(callCnt.ToString() + " " + row.ToString() );
}
The SQL get the results i want,
but the Linq result is like :
1 72662
2 84945
3 264577
4 77655
5 71756
6 76899
7 76719
8 77669
9 152211
10 79168
11 72334
12 71399
13 246031
14 80748
15 77715
.......
This is a limitation of LINQ to SQL, where the OrderBy() must occur after the Distinct(), try this:
IList<int> myResults =
(from t in dbconn.table1
where t.id != -1
select t.id
).Distinct().OrderBy(t => t).Take(50).ToList();
The problem is the way that the Distinct() method works. Unfortunately it can (and usually does) change the order of the items in the list. You need to order the list after calling Distinct().
Try this:
IList<int> myResults =
(
from t in dbconn.table1
where t.id != -1
select t.id
).Distinct().OrderBy(i => i).Take(50).ToList();
Try
var myResults = dbconn.Table1.Where(e => e.id != -1).Select(e => e.id).Distinct()
.OrderBy(t => t).Take(50).ToList();
Related
This question already has answers here:
How do you add an index field to Linq results
(3 answers)
Closed 3 years ago.
SQL:
Select top percent a,b,ROW_NUMBER() over(PARTITION BY a,b order by a,b) as rowsnumber
from Students as s
group by a,b
LINQ:
var students=from p in Students
group p by new{p.a,p.b} into grp
order by grp.Key.a,grp.Key.b
.Select(s=>s.a,s.b).ToList();
I want to this SQL query convert to LINQ but not convert.
var list = FileList.Select((file, index) => new { Index=index, Filename=file });
Maybe so for example.
Like the other answer indicates, the Select method has a handy overload with the index parameter. It requires the method LINQ syntax though (and not the query syntax) So, the following query should do the trick. Note that it combines both: query and method syntax as I tried to keep it close to the code in the question above.
var studentGroups=
from p in Students
group p by new { p.a, p.b };
var students =
from gr in studentGroups
from st in Students
.Where(s => s.a == gr.Key.a && s.b == gr.Key.b)
.Select((s,i) => new { s.a, s.b, s.c, s.d, rn = i + 1 })
orderby st.a, st.b
select st;
I convert your sql query to lambda.
var students = context.GroupBy(g => new { g.A, g.B }).Select((s, index) => new {
s.Key.A,
s.Key.B,
rowsnumber = index + 1
}).Take(10).ToList();
Group by is working like partition by.
Index start from 0, so converting to row number to need add 1.
Take is select TOP 10 rows.
I am trying to convert an SQL query that works, to LINQ equivalent.
Here is the query.
SELECT REPORT_NUMBER,
case when count(distinct STATE) > 1 then 'PENDING'
else case when max(STATE) = 'REPORTED' then 'REPORTED'
else 'PENDING' end end status,
max(REPORT_YEAR)
FROM SAMPLE
GROUP BY REPORT_NUMBER
ORDER BY max(REPORT_YEAR) DESC
So far I created LINQ query that needed a help.
var sums = from foo in db.SAMPLEs
group foo by foo.REPORT_NUMBER into groupings
orderby groupings.Key ascending
select new ReportListModel
{
ReportNbr = groupings.Key,
ReportYear = groupings.Max(g => g.REPORT_YEAR),
ReportSt = groupings.Max(g => g.STATE)
};
Using groupings.Max(g => g.STATE) gives me correct amount of records, but obviously gives me incorrect field result.
How can I create case statement as in SQL query?
You can use inline-if operator like so:
var sums = from foo in db.SAMPLEs
group foo by foo.REPORT_NUMBER into groupings
orderby groupings.Key ascending
select new ReportListModel
{
ReportNbr = groupings.Key,
ReportStatus =
groupings.Select(x => x.STATE).Distinct().Count() > 1 ?
"PENDING" : (
groupings.Max(g => g.STATE) == "REPORTED" ?
"REPORTED" : "PENDING"
)
};
Here i had scenario to get the data in date wise of this month(Present month)
Excepted Result
Date_time sum(collection.amountreceived ) Sum(bank_deposit.depositamount)
1/07/2014 2000 1000
2/07/2014 3000 3000
Schema
bank_deposit
agentid (nvarchar(30))
depositamount (DECIMAL(10,0))
date_time (TIMESTAMP)
collection
customeridn (varchar(30))
amountreceived (DECIMAL(10,0))
date_time (TIMESTAMP)
agentid (nvarchar(30))
Here I used union to get the datetime column data in one column
var unionDateColumn = ((from agent in db.collections select agent.Date_Time)
.Union(from u in db.bank_deposit select u.Date_Time)).ToList();
How can i use this unionDateColumn data for orderby and to get expected output?
Below is query for sum of amount but here my issue is how to
var model = (from coll in db.collections.Where(e => e.AgentID == item.AgentID)
let depositedAmount = db.bank_deposit.Where(d => d.AgentID == item.AgentID ).Sum(c => c.DepositedAmount) == null ? 0
: db.bank_deposit.Where(d => d.AgentID == item.AgentID).Sum(x => x.DepositedAmount)
let collectionAmount = db.collections.Where(c => c.AgentID == item.AgentID).Sum(c => c.AmountReceived) == null ? 0
: db.collections.Where(v => v.AgentID == item.AgentID).Sum(m => m.AmountReceived)
select new GetBalanceAmount
{
DepositedAmount = depositedAmount,
CollectionAmount = collectionAmount
});
I assume you want to order the result by date_time
var result = unoinDateColumn.OrderBy(t=>t.Date_Time).ToList().;
Why FirstOrDefault ? i asume you want every row.
Sajeetharan's example:
var result = unoinDateColumn.OrderBy(t=>t.Date_Time).ToList();
result is the same as "select * from unionDateColumn order by DateTime"
Your example:
model.ToList().OrderByDescending(unoinDateColumn).FirstOrDefault();
is the same as "Select * from model orderby unionDateColumn"
May i ask why you are handling each column seperately? insted of in one large array ?
Handle it in one array, and do like this model.OrderByDescending(x => x.Date_Time);
it will affect the object model and order it like this model = model.sortedBy(model.Date_Time);
Hello I have the following linq statement:
IEnumerable<TabTransaktion> allTransactions
= TabTransaktions1.Union(TabTransaktions2)
.Where(trans => trans.TabVorgang != null).
.OrderBy(tran => tran.TabVorgang.Wirkdatum)
.OrderByDescending(trans2 => trans2.TabVorgang.ID);
But I want the second order by descending when only trans2.TabVorgang.ID equals to 0. So I need a "case" in "order by clause" for LinQ. A LinQ equivalent of something like this:
SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO
I would appreciate any help.
Assuming SalariedFlag is a bool (in SQL of type bit), the two ordering expressions are exclusively mutual. In other words, the main query can be separated into two disjunctive queries and the final result is the union of them:
IEnumerable<TabTransaktion> mainQuery
= TabTransaktions1.Union(TabTransaktions2)
.Where(trans => trans.TabVorgang != null);
var queryOne = mainQuery.Where(p=>p.SalariedFlag ==1)
.OrderByDescending(tran => tran.BusinessEntityID );
var queryTwo = mainQuery.Where(p=>p.SalariedFlag ==0)
.OrderBy(tran => tran.BusinessEntityID);
var finalResult = queryOne.Union(queryTwo);
I have a small problem in my where clause in the linq expression below. If I put the number 3 instead of department.Id I get the desired result but when I use department.Id I get nothing in the resultset.
I also want to get a count for the number of filters for that filter name using the query again using distinct.
var dept = Page.RouteData.Values["department"];
var department = (from d in db.Departments
where d.Name.Replace(" ", "-") == dept
select new {d.Id, d.Name}).FirstOrDefault();
var query = from p in db.Products
join f in db.ProductFilters on p.Id equals f.ProductId into filters
from x in filters.Where(x => x.Product.DepartmentId == department.Id
/* if == 3 it works */)
select new { x.Name, x.Id };
Promoted to answer from comments:
Have you checked that the department instance is as you think it should be after the first linq statement - ie has an Id == 3?
Your first query is not finding any valid department and is therefore returning default which most probably means that departmend.Id == 0.