Need Linq equivalent - vb.net

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)}

Related

How to join linq in c#?

How to convert sql to system.linq?
Select top 100 percent s.a,s.b,s.c,s.d
From table a as s, table b as x
Where
s.a=x.a and s.b=x.b and s.c=x.c
Group by
s.a,s.b,s.c,s.d
As per my understanding of your question; seems like you want to fetch the data in c# and do joining. if so, then you may do as following:
public class tabData
{
public string a {get;set;}
public string b {get;set;}
public string c {get;set;}
public string d {get;set;}
}
List<tabData> tabA = {data of your table a}
List<tabData> tabB = {data of your table b}
var result = from r1 in tabA
join r2 in tabB on new {T1 = r1.a, T2 = r1.b, T3 = r1.c} equals new {T1 = r2.a, T2 = r2.b, T3 = r2.c}
group r1 by new
{
aa = r1.a,
bb = r1.b,
cc = r1.c,
dd = r1.d
} into g
select new
{
a = g.key.aa,
b = g.key.bb,
c = g.key.cc,
d = g.key.dd
}
I think you are asking how to join in linq as you would in sql, if so, please see below:
var query =
from abc in tbl1
join def in tbl2 on tbl1.PK equals tbl2.FK
select new { ABC = abc, DEF = def };

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)
};

Nhibernate Join 2 QueryOver

I can't find how to join two different QueryOver, group by and perform a substraction in the select.
Say you have :
public class EntityA
{
public virtual int Id;
public virtual string Reference;
public virtual int Quantity;
[Some properties]
}
public class EntityB
{
public virtual int Id;
public virtual int EntityAId;
[Some properties]
}
If i translate my query in pseudo-SQL, i would like to have :
SELECT A.Id, A.Reference, A.Quantity - COALESCE(DERIV_B.TOTAL, 0)
FROM EntityA A
LEFT JOIN (
SELECT B.EntityAId, COUNT(B.Id) AS TOTAL
FROM EntityB B
GROUP BY B.EntityAId) DERIV_B
ON A.Id = DERIV_B.EntityAId
WHERE (A.Quantity - COALESCE(DERIV_B.TOTAL, 0)) >= 0
I can have the subquery on EntityB via QueryOver, but i can't join on EntityA :
var entitiesB = GetCurrentSession().QueryOver<EntityB>().SelectList(select => select.SelectGroup(x => x.EntityAId).SelectCount(x => x.Id));
var entitiesA = GetCurrentSession().QueryOver<EntityA>(). ???
I tried to store the entitiesB in an alias and the perform a JoinAlias on it but i have an exception because it can't retrieve my alias.
Do you have any solution ?
I don't want to create a reference between these two entites.
Short answer is not , you can't do QueryOver if your entities are not connected through model.
One solution would be to use NHibernate.Linq and subqueries
var session = GetCurrentSession();
var entityBQuery = session.Query<EntityB>();
var entityAQuery = session.Query<EntityA>()
.Select(eA=>new { Id = eA.Id,
Description = eA.Description,
Quantity = eA.Quantity - entityBQuery.Where(eb=>eb.EntityAId = eA.Id).Count()
});

What is the equivalent DISTINCT(sql server) in the Linq

I have a Table(Send) with columns(Id, UserId,SendDate) and another table(Receive) with columns(Id,SendId,UserName).
I want show all records in SendTable with all RecieveUserName.
for example.
(Send)
1 1 2013
2 2 2013
(Recieve)
1 1 Jack
2 1 Ema
3 2 Alex
4 2 Sara
Result
1 1 2013 Jack, Ema
2 2 2013 Alex, Sara
I use this query in SqlServer (The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement)
SELECT DISTINCT c2.Id,
(SELECT STR( UserName )+ ','
FROM dbo.Reciver c1
WHERE c1.SendId = c2.id FOR XML PATH('')) Concatenated, c2.SendDate, c2.UserId
FROM dbo.Send AS c2 INNER JOIN
dbo.Reciver ON c2.Id = dbo.Reciver.SendId
How do this query in Linq?
Distinct is also available in LINQ.
For example
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 10 },
new Product { Name = "lemon", Code = 9 } };
var lstDistProduct = products.Distinct();
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}
Will return all rows.
var list1 = products.DistinctBy(x=> x.Code);
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}
will return 9 and 4
It doesn't seem to me that you need to use Distinct in this Linq query. Assuming you have the relationships between tables set up on your linq datacontext, you can do something like this:
var result = from s in context.Send
select new {
id = s.Id,
userId = s.UserId,
date = s.SendDate,
users = s.Receive.Select(u => u.UserName)
}
Note: users will an IEnumerable<String> - you can use string.Join() on the client to join the names into a string.
Update
To return users as a string to first need to 'switch' to Linq To Objects by calling AsEnumerable() or ToList() and the Linq to Sql query.
var output = from s in result.AsEnumerable()
select new {
id = s.id,
userId = s.userId,
date = s.date,
users = string.Join(", ", s.users)
}
Also see Gert Arnolds answer for a good explanation.
What you want can only be done in two steps. Not because of the DISTINCT, but because of the FOR XML. The C# equivalent of the latter is String.Join(), but you can't use that in a linq to entities statement directly. So you must collect the required data first, then switch to linq to objects (by applying AsEnumerable) and then do the concatenation and distinct:
db.Sends
.Where(s => s.Receivers.Any())
.Select(s => new {
s.Id,
Concatenated = s.Receivers.Select(r => r.UserName)
s.SendDate,
s.UserId
})
.AsEnumerable()
.Select(x => new {
s.Id,
Concatenated = String.Join(", ", x.Concatenated)
s.SendDate,
s.UserId
})
.Distinct()

SQL to LINQ Group by convertion

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
};