Sql Query to Linq using IN - c#

I have a Sql Query like :
select distinct FROM_EMAILID,FROM_COUNTRY from SURVEY_VISITORS
where FROM_COUNTRY IN
(
select top 1 FROM_COUNTRY as FROM_COUNTRY from SURVEY_VISITORS
where FROM_COUNTRY<>'undefined'
group by FROM_COUNTRY order by COUNT(*) desc
)
I'm unable to handle with IN Operator.
Any help would be greatly appreciated.
For the sub-Query,I've tried this way :
var innerQuery = (from t in VDC.SURVEY_VISITORS
group t by new
{
t.FROM_COUNTRY
} into g
orderby
g.Count() descending
select new
{
VisitorCount = (Int64?)g.Count(),
Country = g.Key.FROM_COUNTRY
}).FirstOrDefault();

var innerQuery = (from t in VDC.SURVEY_VISITORS
group t by new
{
t.FROM_COUNTRY
} into g
orderby
g.Count() descending
select new
{
VisitorCount = (Int64?)g.Count(),
Country = g.Key.FROM_COUNTRY
}).FirstOrDefault();
var result = (from xx in VDC.SURVEY_VISITORS
where ((innerQuery.Country.Contains(xx.FROM_COUNTRY)) && xx.TEMPLATE_ID == RecentBlastedTemplate.TEMPLATE_ID)
select new
{
xx.FROM_COUNTRY,
xx.FROM_EMAILID
}).Distinct().ToList();

Related

Select Values from two tables using Linq

Hi I know this has been asked plenty of times, I'm not getting it through my skull
How to select Values from several tables
I made these two Linq queries
First
r = (from d in db.stageManagers
where d.profileID == UserID && d.verticalID == VerticalID
select new StageModels()
{
UserId = d.profileID,
VerticalId = (int)d.verticalID,
VerticalStageID = d.stageID
}).FirstOrDefault();
Second
r = (from d in db.stageManagerVerticals
where d.ID == r.VerticalId
select new StageModels()
{
VerticalName = d.verticalName
}
).FirstOrDefault();
I want to make them one statement since they add data to one model and the tables they query have a Pk Fk relationship
In the first block d.verticalId is what I use to get the value(Name) in the secondblock, d.verticalId is primary key to stageManagerVerticals and foreign key in stageManager, How can i join these queries ?
I tried this:
r = (from d in db.stageManagers
join c in db.stageManagerVerticals on d.stageID equals c.ID
where d.profileID == UserID && d.verticalID == VerticalID
select new StageModels()
{
UserId = d.profileID,
VerticalId = (int)d.verticalID,
VerticalStageID = d.stageID;
VerticalName = c.verticalName
}
).FirstOrDefault();
try with JOIN in LINQ to select values from more than one table
eg:
var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };
var leftOuterJoin=(c in categories
join p in products on c.ID equals p.CategoryID into t
from temp in t.DefaultIfEmpty()
select new { ProductName = p.Name, Category = c.Name }
).ToList();
You can utilize the Navigational Properties,
var r = db.stageManagers.Where(x => x.profileID == UserID && x.verticalID == VerticalID).
Select(
d => new StageModels() {
UserID = d.profileID,
VerticalID = (int)d.verticalID,
VerticalStageID = d.stageID,
VerticalName = d.stageManagerVertical.verticalName
}
).FirstOrDefault();

Count in select query of Linq to SQL

I am trying to convert below SQL query into Linq.
select eg.userid, eg.groupid, count(r.RID) as RecipientCount
from eg
join g on eg.groupid = g.groupid
join r on g.RID = r.RID
where eg.UserId = '7F813844-3B93-418E-8141-654082C4E37D'
and eg.IsDeleted = 0
and r.Isdeleted = 0
group by eg.groupid
Above query runs properly in SQL.
My Linq code is:
var v = from eml in dc.egs
join recpingroup in dc.g on eml.GroupID equals recpingroup.GroupID
where eml.aspnet_User.LoweredUserName.Equals(strUserName.ToLower())
&& !eml.IsDeleted
&& !recpingroup.r.IsDeleted
select new Info()
{
CreateDt = eml.CreateDt.ToShortDateString(),
UserId = eml.UserId.ToString(),
LastUpdateDt = eml.LastUpdateDt.ToShortDateString(),
Username = eml.aspnet_User.UserName,
GroupDescription = eml.GroupDescription,
GroupID = eml.GroupID.ToString().ToUpper(),
GroupName = eml.GroupName,
Count = dc.g.Count(r1 => r1.GroupID.Equals(eml.GroupID) && !r1.r.IsDeleted)
};
where dc is my DataContext.
But I am having problems in the last property i.e. Count is coming wrong. I want the counts of recipients from recpingroup.r as RecipientCount.
Also note that tables are linked in SQL internally by PK and FK references.
try following
Count = (from x in dc.g where(r1 => r1.GroupID.Equals(eml.GroupID) && !r1.r.IsDeleted) select x.g).count()

Linq to SQL using group By, and order by count

This is mysql query:
SELECT count(PVersion), PVersion
FROM [Products].[dbo].[Active_Details]
group by PVersion
order by count(PVersion);
What will be its LINQ to SQL.
Try this:
var product =
from p in yourContext.Active_Details
group p by p.PVersion into pgroup
let count = pgroup.Count()
orderby count
select new { Count = count, PVersion = pgroup.Key };
SELECT count(ProductVersion), ProductVersion , ProductID , SubProductID
FROM [do-not-delete-accounts].[dbo].[Activation_Details]
group by ProductVersion,ProductID,SubProductID
order by count(ProductVersion);
var query =
from p in yourContext.Activation_Details
group p by new
{
ProductVersion = p.ProductVersion,
ProductID = p.ProductID,
SubProductID = p.SubProductID
}
into pgroup
let count = pgroup.Count()
orderby count
select new
{
Count = count,
ProductVersion = pgroup.Key.ProductVersion,
ProductID = pgroup.Key.ProductID,
SubProductID = pgroup.Key.SubProductID
};
Should be a group into:
var product = (
from p in yourContext.Active_Details
group p by p.PVersion into pgroup
select new { VersionCount= pgroup.Count(), pgroup.Key }
).OrderBy(x=>x.VersionCount);
Here is a MSDN Resource with examples

How to generate SQL COUNT(*) OVER (PARTITION BY {ColumnName}) in LINQ-to-SQL?

Is it possible to generate the following SQL query by using LINQ-to-SQL query expression or method chains which is defer-executable?
Data Structure
alt text http://www.freeimagehosting.net/uploads/e062a48837.jpg
Select Distinct ClassRoomTitle,
Count(*) Over(Partition By ClassRoomNo) As [No Sessions Per Room],
TeacherName,
Count(*) Over(Partition By ClassRoomNo, TeacherName) As [No Sessions Per Teacher] From ClassRoom
Expected Result
alt text http://www.freeimagehosting.net/uploads/47a79fea8b.jpg
Try this:
var vGroup = from p in ClassRoom
group p by new { p.ClassRoomNo, p.TeacherName }
into g
from i in g
select new
{
i.ClassRoomNo,
i.TeacherName,
i.ClassRoomTitle,
NoSessionsPerTeacher = g.Count()
};
var pGroup = from p in vGroup
group p by new { p.ClassRoomNo }
into g
from i in g
select new
{
i.ClassRoomTitle,
NoSessionsPerRoom = g.Count(),
i.TeacherName,
i.NoSessionsPerTeacher
};
var result = pGroup.OrderBy(p => p.ClassRoomNo).ThenBy(p => p.TeacherName);
I didn't test the above but you can check my original code in case I got something wrong in the rewrite:
var vGroup = from p in Products
group p by new { p.ProductId, p.VariantId }
into g
from i in g
select new
{
i.ProductId,
i.VariantId,
VariantCount = g.Count()
};
var pGroup = from p in vGroup
group p by new { p.ProductId }
into g
from i in g
select new
{
i.ProductId,
ProductCount = g.Count(),
i.VariantId,
i.VariantCount
};
var result = pGroup.OrderBy(p => p.ProductId).ThenBy(p => p.VariantId);
var classRooms = from c in context.ClassRooms
group c by new {c.ClassRoomNo} into room
select new {
Title = room.First().ClassRoomTitle,
NoSessions = room.Count(),
Teachers = from cr in room
group cr by new {cr.TeacherName} into t
select new {
Teacher = t.Key,
NoSessions = t.Count()
}
};
A bit more structured than the posted expected result, but I find that to be better.
You can always use SelectMany if you want to go back to unstructured:
var unstructured = classRooms
.SelectMany(c=> c.Teachers.Select( t=> new {
Title = c.Title,
SessionsPerRoom = c.NoSessions,
Teacher = t.Teacher,
SessionsPerTeacher = t.NoSessions
});

Linq query with a Conditional WHERE Clause

I am new to LINQ so apologises upfront
I have the following Linq query :-
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys
on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a =>
a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
I need to include a where clause in the above query ... only if a variable called
BranchKeySelected is ""
I have tried using an If Else statement and have the same above query duplicated with
one containing a where clause and one NOT. ...But When I do this .. then OrdersByBranches
is NOT available outside of the IF Statement
Would be grateful for any help
Regards
Ghost
var OrdersByBranches =
from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
orderby a.Date
group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
select new {
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};
if(string.IsNullOrEmpty(BranchKeySelected ))
{
OrdersByBranches = OrdersByBranches.Where(/*blbabla*/);
}
return OrdersByBranches;
Try (and my linq is not polished)
var OrdersByBranches = from a in AllOrders
join b in AllBranchKeys on a.BranchKey equals b.BranchKey
where b.BranchKeySelected.Contains("")
orderby a.Date group a by new
{
a.Date,
a.paymentMethod
}
into BranchOrderGrouped
select new
{
BranchOrderGrouped.Key.Date,
CurrencyAmount = BranchOrderGrouped.Sum(a => a.CurrencyAmount),
BranchOrderGrouped.Key.paymentMethod
};

Categories

Resources