LINQ TO SQL Subquery - c#

I am learning LINQ to SQL. And I want to write a LINQ TO SQL Query for the following:
SELECT TOP 1 * From
(select Top 2 * from Data ORDER BY ID DESC)
ORDER BY ID
According to my understanding it is written something like this;
GridView1.DataSource = from ( from data in dbCon.Data ORDER BY data.ID DESC
select Top 2 *)ORDER BY data.ID
select TOP 1 * ;
but it is not correct. Can anybody tell me the correct syntax? and links that can help me learn LINQ TO SQL Syntax for writing subqueries?

This should work for you:-
var result = (from x in
((from data in db.DATA orderby data.ID descending select data).Take(2))
orderby x.ID
select x).FirstOrDefault();

Try this:
var query = (from x in db.Data
select x).OrderByDescending(x=> x.Id).Take(2);
var query2 = (from y in query
SELECT y).OrderByDescending(y=> y.Id).Take(1);

Related

Nested Select MySQL statements to LINQ

I'm trying to convert the following MySQL statement in to LINQ query format
SELECT * FROM table1 WHERE table1.id IN (SELECT c_id FROM table2 WHERE a_id IN (1, 49) GROUP BY c_id HAVING COUNT(*) = 2) ORDER BY name
Got as far as this, but I'm drawing a blank on how to handle the IN and 2nd SELECT statement
myItems = from c in table1
let id = c.id
where ????
orderby c.name
select c;
Would appreciate some guidance with this please
Try this:
var ids=new[]{1,49};
var innerquery=table2.Where(e=>ids.Contains(e.a_id))
.GroupBy(e=>e.c_id)
.Where(g=>g.Count()==2)
.Select(g=>g.Key);
var myItems = from c in table1
where innerquery.Contains(c.id)
orderby c.name
select c;
First define your inner query,after the group by you will get a collection of IGrouping<TKey, TElement>> that represent a collection of objects that have a common key, filter the groups choosing only those where count==2, and select the keys of those groups. The second part is really easy to understand. I split the process in two queries to do it more readable, but you can merge both query in one.

Use subquery in linq query

How can I construct the below sql query in linq query to get the results ?
SELECT PageNumber from LMS_SurveyQuestion WHERE SurveyQuestionID IN
(SELECT SurveyQuestionID from LMS_SurveyQuestionOptionChoice
WHERE NextPageNumber = 4) and SurveyID = 1
Have a look at this article. Basically, if you want to implement SQL IN query in LINQ, you need to construct an inner query first, and then use the Contains() method. Here's my attempt:
var innerQuery = (from log in LMS_SurveyQuestionOptionChoice where log.NextPageNumber = 4 select log.SurveyQuestionID);
var result = (from f in LMS_SurveyQuestion where innerQuery.Contains(f.SurveyQuestionID) && f.SurveyID = 1 select f);
Hope this will help.
try this
var result = from l in LMS_SurveyQuestion
let lsq = from l_S in LMS_SurveyQuestionOptionChoice
where l_S.NextPageNumber = 4
select l_S.SurveyQuestionID
where lsq.Contains(l.SurveyQuestionID) and l.surveyid = 1
select l.PageNumber;

C# Linq query where Table A column is not equal/doesnt math Table B column join

I have an issue with a c# linq query where I use the != operator, it works well in SQL but when I write the same query in C# it returns a different result, which is the correct way to the the results where table a column doesn't match table b column. Please see my sql query below and then my c# query.
SELECT tba.ID,fa.accountnumber,tba.Account_Number,fa.new_legalname,tba.Legal_Name,fa.new_deliverystatusname, fa.new_deliverystatus,tba.Delivery_Charge
FROM [CRM_Embrace_Integration].[dbo].[CRM_Tarsus_Debtors_Accounts] tba
inner join CRM_MBT_GROUP.dbo.FilteredAccount fa
ON fa.accountnumber collate database_default = tba.Account_Number
where fa.new_legalname collate database_default != tba.Legal_Name
and the Linq query looks like this
var sqlJoinQuery = from accCRM in todaysCRMAccounts
join accSQL in todaysCRMViewAccounts
on accCRM.Account_Number equals accSQL.accountnumber
where accCRM.Legal_Name != accSQL.new_legalname
select new { accCRM.Legal_Name, accSQL.new_legalname };
The SQL query returns the correct result as I want where legal_name(table A) is not equals to legal_name(table B) is the other table.
The Linq query return incorrect result, please assist.
I suggest to try the following Linq as you want the data that aren't in table 2:
var result1 = (from m in db1.Table1
select m).ToList();
var result2 = (from m in db2.Table2
select m).ToList();
var finalResult = (from m in result1
where !(from k in result2
select k.Id).Contains(m.Id)
select m).ToList();
The above will return that aren't in Table2. I hope, this is what you wanted.
Your SQL shows you asking for where they are equal. The LINQ shows you asking for when they are not equal.

is it possible to have a select statement in the resultset of a linq query?

I have a query like the following:
select column_a, (select column_a from table_b where b.column_c = a.column_c) column_b
from table_a a where a.test = 1 order by a.number
I know I can perform joins in linq but is there something similar like this in linq ?
This is a straightforward translation of the SQL statement:
from a in table_a
where a.test == 1
orderby a.number
let column_b = (from b in table_b where b.column_c == a.column_c select b.column_a).SingleOrDefault()
select new { a.column_a, column_b }
Keep in mind that this is a nested loop, so it has quadratic performance if it's a simple LINQ to Objects query. In the T-SQL example, the optimizer knows how to turn the subquery into a join anyway.
Use the 'Join' method: http://msdn.microsoft.com/en-us/library/bb311040.aspx
In declarative syntax:
from item_a in table_a
join item_b in table_b on item_a.column_c equals item_b.column_c
where item_a.test == 1
orderby item_a.number
select new {column_a = item_a.column_a, column_b = item_b.column_a};
And in method syntax:
table_a.Where (item_a => item_a.test == 1)
.Join(table_b,
(item_a) => item_a.column_c,
(item_b) => item_b.column_c,
(item_a, item_b) => new { column_a = item_a.column_a, column_b = item_b.column_a });
See this gist for a runnable LinqPad snippet.

Linq query for a nested select statement with grouping and distinct

I'd like to translate the following SQL statement into a linq query:
select COUNT(*), itemid, globalid, title, preview, previewimage, previewimage_alt, link
from (
select distinct Id, itemid, globalid, title, preview, previewimage, previewimage_alt,
(select top 1 link from LikeCounter where GlobalId=x.GlobalId) as link
from [LikeCounter] x
where PortalId=1 and LanguageId=1
) as t
GROUP BY itemid, globalid, title, preview, previewimage, previewimage_alt, link
ORDER BY COUNT(*) desc
The query is over a view that holds records of objects being "liked". Since the objects can be published in multiple places, and the view was setup to allow for filtering for a certain place, it requires a distinct before grouping the records to find out the view count (that's the reason for the additional query for the "link" column).
Is a nested SELECT statement possible in one linq statement?
The inner query is no problem:
(from x in LikeCounter
where x.PortalId==1 && x.LanguageId==1
select new {x.Id, x.ItemId, x.GlobalId, x.LanguageId, x.Title, x.Preview, x.PreviewImage_alt,
Morelink=(from y in LikeCounter
where y.GlobalId==x.GlobalId
select y.Morelink).FirstOrDefault()
}).Distinct()
But is there a way to extend this with the grouping of the distinct records, that results in just one query to the database ?
Thanks in advance for any input...
Nina
Edit:
the following query almost returns what I want -- but produces multiple queries to the SQL server:
(from y in
((from x in LikeCounter
where x.PortalId==1 && x.LanguageId==1
select new {x.Id, x.ItemId, x.GlobalId, x.LanguageId, x.Title, x.Preview, x.PreviewImage_alt,
Link=(from y in Xparo_LikeCounter
where y.GlobalId==x.GlobalId
select y.Link).FirstOrDefault()
}).Distinct())
group y by y.GlobalId into grp
select new {Data=grp, Count= grp.Count()}).OrderByDescending (x => x.Count)
I Think the below should work but i can't really test it. No idea how many queries it would take either
from subq in (from x in LikeCounter
where x.PortalId==1 && x.LanguageId==1
select new {x.Id, x.ItemId, x.GlobalId, x.LanguageId, x.Title, x.Preview, x.PreviewImage_alt,
Morelink=(from y in LikeCounter
where y.GlobalId==x.GlobalId
select y.Morelink).FirstOrDefault()
}).Distinct()
group subq by new {TheCount = subq.Id.Count(), subq.Id, subq.ItemId, subq.GlobalId, subq.LanguageId, subq.Title, subq.Preview, subq.PreviewImage_alt, subq.Morelink } into grouped
order by grouped.TheCount descending;

Categories