SQL to LINQ Group by convertion - sql

I have an SQL statement and I want to convert it to LINQ. The problem now is that I don't know how to group by it in LINQ.
Here is the code.
In SQL
select plp.ProspectsListID, p.Prospect_PII_Key
from ProspectListProspect plp
join Prospects p
on p.ProspectsID = plp.ProspectsID
group by plp.ProspectsListID,p.Prospect_PII_Key
In LINQ
var list1 = from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
select new
{
ProspectID = plp.ProspectsListID,
Prospect_PII_Key = p.Prospect_PII_Key
};
thanks
Jason

tyr this
var list1 = from item in
(
from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
select new
{
ProspectID = plp.ProspectsListID,
Prospect_PII_Key = p.Prospect_PII_Key
}
)
group item by new {item.ProspectID ,item.Prospect_PII_Key } into grp
select new
{
ProspectID = grp.ProspectsListID,
Prospect_PII_Key = grp.Prospect_PII_Key
}
;

Check this
var list1 = from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
Group By Key = New With {plp.ProspectsListID,p.Prospect_PII_Key} Into Group
Select Group;

var list1 = from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
group p by new {plp.ProspectsListID,p.Prospect_PII_Key} into g
select new
{
ProspectID = g.Key.ProspectsListID,
Prospect_PII_Key = g.Key.Prospect_PII_Key
};

Related

LINQ and Lambda, query based on an array

I have this model and I want to write a where clause that query specific results based on and array, for example I want to show only the song that has an id in the array [1, 3, 7, 8]:
I wrote the expression below but I don't know how to write the where statement:
var model = from c in _db.Categories
from co in _db.Composers
from k in _db.Keys
from p in _db.Poets
from si in _db.Singers
from t in _db.Types
join s in _db.Songs on
new
{
Catid = c.id,
Comid = co.id,
Keyid = k.id,
Poetid = p.id,
Singerid = si.id,
Typeid = t.id
}
equals
new
{
Catid = s.CategoryId,
Comid = s.ComposerId,
Keyid = s.KeymId,
Poetid = s.PoetId,
Singerid = s.SingerId,
Typeid = s.TypeId
}
where
............
select new SongViewModel
{
id = s.id,
Name = s.Name,
Lyric = s.Lyric,
Chord = s.Chord,
Note = s.Note,
Audio = s.Audio,
Lycho = s.Lycho,
Likes = s.Likes,
Dislikes = s.Dislikes,
Category = c.Name,
Composer = co.Name,
Keym = k.Name,
Poet = p.Name,
Singer = si.Name,
Type = t.Name
};
Try this:
var ids = new List<int> {1,3,7,8};
...
where ids.Contains(s.Id)
select
...

SQL to LINQ query equivalent

Hello I need to crate linq query from this SQL:
SQL:
select
p.id,
p.Name,
sum(h.Hour)
from
dbo.Hour h
INNER JOIN dbo.ProjectView p ON h.ProjectId = p.Id
WHERE
h.PeopleId = 7999
group by
p.Name, p.Id
LINQ: I tried this but it is not the same:
var query = from hours in _hourRepository.GetAll()
join proj in _projectRepository.GetAll() on hours.ProjectId equals proj.Id
where hours.PeopleId == personId
group hours by new { proj.Id, proj.Name, proj.Flag, hours.Hours } into g
select new PopleProjectsSumDto
{
Id = g.Key.Id,
Name = g.Key.Name,
Flag = g.Key.Flag,
Hours = g.Sum(h => h.Hours)
};
OK i find solution by removing hours from group:
LINQ:
var query = from hours in _hourRepository.GetAll()
join proj in _projectRepository.GetAll() on hours.ProjectId equals proj.Id
where hours.PeopleId == personId
group hours by new { proj.Id, proj.Name, proj.Flag } into g
select new PopleProjectsSumDto
{
Id = g.Key.Id,
Name = g.Key.Name,
Flag = g.Key.Flag,
Hours = g.Sum(h => h.Hours)
};

Is this possible with Dapper?

If you have a Customer object that has a List<Orders> property how can you select the customers you want and then apply the orders for that customer to the List<Orders> property for each one?
The only way I can think is to loop over customers and hit the database N times for the relevant orders against that customer.
var sql = #"
select * from Customers
select * from Orders where CustomerId = #id";
using (var multi = connection.QueryMultiple(sql))
{
var customers = multi.Read<Customer>();
//Get orders for each result in customers and apply
//Customer.Orders property to result
var orders = multi.Read<Order>().ToList();
}
You should use multi-mapping. From Dapper documentation:
var sql =
#"select * from #Posts p
left join #Users u on u.Id = p.OwnerId
Order by p.Id";
var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});
var post = data.First();
post.Content.IsEqualTo("Sams Post1");
post.Id.IsEqualTo(1);
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo(99);
In your code Users will be Customers, and Orders will be Posts
Edit I realize that this is not exactly what your want. So, in your case you can use QueryMultiple, but then matching the records from both lists with linq, avoiding hitting the Db N times:
var sql = #"select * from Customers
select * from Orders";
using (var multi = connection.QueryMultiple(sql))
{
var customer = multi.Read<Customer>().Single();
var orders = multi.Read<Order>().ToList();
}
foreach c in customers {
c.Orders = (from rec in orders where rec.CustomerId == c.Id select rec).ToList()
}
Edit refactor for better performance if you have several filter in Customers
var customers = connection.Query<Customer>("select * from Customers
where blah, blah, blah, blah, .. ").ToList();
var orders = connection.Query<Order>("select * from Order where CustomerID in #Ids",
new { Ids = (from rec in customers select rec.Id).ToList()}).ToList();
foreach c in customers {
c.Orders = (from rec in orders where rec.CustomerId == c.Id select rec).ToList()
}

Join Subquery result in Linq

I am posting one more doubt of mine:
Is there a way by which we can use the result of one query and then join the same further just like we do in SQL:
SELECT Applications.* , ApplicationFees.ApplicationNo, ApplicationFees.AccountFundDate1,ApplicationFees.AccountFundDate2 ,ApplicationFees.AccountFundDate3 , ApplicationFees.AccountCloseDate1, ApplicationFees.AccountCloseDate2,ApplicationFees.AccountCloseDate3,
isnull(SUBQRY11.AMNT ,0) as SCMSFEE1R,
isnull(SUBQRY12.AMNT,0) as SCMSFEE2R,
Left Join
(
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT, SUM(Amount) as AMNT
FROM Payments where (FEETYPE=1 AND FeePosition=1) and (FeeDate>='2011-01-01')
and (FeeDate<='2012-01-01')
GROUP BY ApplicationNo
)SUBQRY11
ON ApplicationFees.ApplicationNo= SUBQRY11.ApplicationNo
Left Join
(
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT2, SUM(Amount) as AMNT
FROM Payments where (FEETYPE=1 AND FeePosition=2) and (FeeDate>='2011-01-01')
and (FeeDate<='2012-01-01')
GROUP BY ApplicationNo )SUBQRY12 ON ApplicationFees.ApplicationNo=SUBQRY12.ApplicationNo
I want to avoid the same in foreach of the query as that will be quite time consuming.
Yes, you can join sub queries. Like this:
var query = from f in db.ApplicationFees
join sub in (from p in db.Payments
where p.Type == 1 && p.Position == 1 &&
p.Date >= fromDate && p.Date <= toDate
group p by p.ApplicationNo into g
select new {
ApplicationNo = g.Key,
CNT = g.Count(),
AMNT = g.Sum(x => x.Amount)
})
on f.ApplicationNo equals sub.ApplicationNo into feePayments
select new { Fee = f, Payments = feePayments };
But writing it in single query is not very maintainable. Consider to compose your query from sub-queries defined separately:
var payments = from p in db.Payments
where p.Type == 1 && p.Position == 1 &&
p.Date >= fromDate && p.Date <= toDate
group p by p.ApplicationNo into g
select new {
ApplicationNo = g.Key,
CNT = g.Count(),
AMNT = g.Sum(x => x.Amount)
};
var query = from f in db.ApplicationFees
join p in payments
on f.ApplicationNo equals p.ApplicationNo into feePayments
select new { Fee = f, Payments = feePayments };

Need Linq equivalent

Help in find the Linq equivalent on the below sql query:
select sum(weight) from (
select weight from pers p
join list l on l.persindex= p.persindex
group by p.persindex,weight) a
from p in context.pers
join l in context.list on l.persindex equals p.persindex
group by new
{ p.persindex,
l.weight
} into myGroup
select new()
{ Key = myGroup.Key,
GroupSum = myGroup.sum(x=>x.weight)
}
I guess that's what you need:
public int CalcWeight(IEnumerable<Person> pers, IEnumerable<Person> list)
{
return
pers
.Join(list, p=>p.PersIndex, l=>l.PersIndex, (p, l) => new {p.PersIndex, l.Weight})
.GroupBy( a => new {a.PersIndex, a.Weight})
.Sum(group=>group.Key.Weight);
}
Data class Person is decalerd like this:
public class Person
{
public int PersIndex;
public int Weight;
}
VB.NET version
Dim customerList = From p In pers
Group Join l In list On
p.persindex Equals l.persindex
Into joineddata = Group,
TotalOweight = Sum(p.weight)
Select p.persindex, TotalOweight
Try : Linquer SQL to LINQ convertion tool :
from p in pers
joins l in list on l.persindex equals p.persindex
group by new {p.persindex,l.weight } into grp
select new { sum = grp.sum(x=>x.weight)}