I have the following Tables
+--------+ +---------+ +---------+
| Class |1 N| Student |1 N| Test |
+--------+<--->+---------+<--->+---------+
|ClassID | |ClassID | |TestID |
|Desc | |StudentID| |StudentID|
+--------+ |Name | |Name |
+---------+ |Score |
+---------+
and I need to determine the total score of the first student of a class. there can be one, multiple or none existing tests for this student
So the result should look like
ClassDesc | StudentName | ScoreCount
----------+-------------+-----------
C1 | Max | 201
C2 | Tom | null
I have the following code
using (myEntities ctx = new myEntities())
{
var Reslut = ctx.Class
.Select(x => new
{
ClassDesc = x.Desc,
StudentName = x.Student.FirstOrDefault().Name,
ScoreCount = x.Student.FirstOrDefault().Test.Sum(t => t.Score) //Error here
}).ToList();
}
but it gives me the error
Unknown column 'Project1.ClassID' in 'where clause'
Try the following:
var result = (from cls in ctx.Class
join stdt in ctx.Student on cls.ClassID equals stdt.ClassID
select new
{
ClassDesc = cls.Desc,
StudentName = stdt.Name,
ScoreCount = stdt.Test.Sum(t => t.Score)
}).ToList();
Which should generate SQL similar to the following:
SELECT
Class.ClassID,
Class.[Desc],
Student.Name,
(
SELECT
SUM(Test.Score)
FROM dbo.Test
WHERE Student.StudentID = Test.StudentID
) AS ScoreSum
FROM dbo.Class
INNER JOIN dbo.Student ON Class.ClassID = Student.ClassID
Related
im doing this query on sql and it works, but how do i make it to Linq ?
select b.Name,a.idempresa,count(1) as cuenta from Descarga_XML_recepcion_V2 as a
inner join EnterpriseSGE as b on a.idempresa = b.EnterpriseSGEId group by idempresa,b.name
this is what it should bring
name1 | 5041 | 583
name2 | 4031 | 1730
name3 | 5042 | 640
name4 | 4034 | 300
name5 | 6047 | 861
name6 | 5043 | 187
name7 | 4033 | 318
A straight forward translation of the SQL into LINQ yields:
var ans = from a in Descarga_XML_recepcion_V2
join b in EnterpriseSGE on a.idempresa equals b.EnterpriseSGEId
group 1 by new { a.idempresa, b.name } into ingroup
select new {
ingroup.Key.idempresa,
ingroup.Key.name,
cuenta = ingroup.Count()
};
Try :
var results = (from a in Descarga_XML_recepcion_V2
join b in EnterpriseSGE on a.idempresa equal b.EnterpriseSGEId
select new { a = a, b = b})
.GroupBy(x => new { idempresa = x.a.idempresa, name = x.b.name})
.Select(x => new {name = x.Key.name, idempresa = x.Key.idempressa, count = x.Count()})
.ToList();
I'm trying to get the output of the following query into a Linq query
SELECT SearchQueries.Query,
Clicks.Name,
COUNT (SearchQueries.Query) AS Hits
FROM SearchQueries
INNER JOIN Clicks ON Clicks.SearchqueryId = SearchQueries.Id
GROUP BY SearchQueries.Query, Clicks.Name
ORDER BY Hits DESC
But I can't seem to figure out how to do this;
this is what I have so far
var result =
_db.Clicks.Select(q => q)
.GroupBy(q => q.Name, g => g.Searchquery.Query)
.ToDictionary(g=> g.Key, g => g);
but how would I continue?
the result is something like this:
+---------------+-------------------+------+
|Query | Name | Hits |
+---------------+-------------------+------+
|tag | dnfsklmfnsd | 53 |
|tag2 | dgsqfsdf | 17 |
+---------------+-------------------+------+
The original tables looks like following
SearchQueries;
+---+-------+
|Id | Query |
+---+-------+
| 1 | tag | x 53
| 2 | tag2 | x 17
+---+-------+
Clicks;
+---+-------------------+---------------+
|Id | Name | SearchqueryId |
+---+-------------------+---------------+
| 1 | dnfsklmfnsd | 1 |
| 2 | dgsqfsdf | 2 |
+---+-------------------+---------------+
Try to use GroupBy and Count: (I changed the order to using SearchQueries as "base table" in the expression, just to make it more easy to compare to the SQL-statement)
var result =
_db.SearchQueries
.GroupBy(sq => new { name = sq.Clicks.Name, query = sq.Query)
.Select(sq => new {
Query = sq.Query,
Name = sq.Clicks.Name,
Hits = sq.Count()
})
.OrderByDescending(sq => sq.Hits);
Well, if you have a navigation property Searchquery on Click, as it looks like, you can do
var result =
_db.Clicks
.GroupBy(m => new {name = m.Name, query = m.Searchquery.Query)
.Select(g => new {
Query = g.Key.query,
Name = g.Key.name,
Hits = g.Count()
});
I have a collection like this:
Order //Collection
|-OrderId
|-DateOfOrder
|-PartyName
|-OrderDetails //Collection
| |-ItemName
| |-Quantity
| |-Rate
| |-Amount
|-Dispatch //Collection
| |-InvoiceNo
| |-DateOfDispatch
| |-DispatchDetails //Collection
| | |-ItemName
| | |-Quantity
| | |-Rate
| | |-Amount
Now I want to flatten this collection, so that I can show data in below mentioned pattern:
OrderId | DateOfOrder | PartyName | InvoiceNo | DateOfDispatch | Dispatch ItemName | Dispatch Quantity | Dispatch Rate | Dispatch Amount
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
I have tried:
Orders = new ObservableCollection<Order>(orderService.GetAllOrders()
.SelectMany(x => x.Dispatches)
.SelectMany(x => x.DispatchDetails)
.ToList()
);
The relation between OrderDetails and DispatchDetails is not clear to me, and DispatchItemTransactions seems to be missing from your data structure. Anyway, I hope you find this simple approach useful:
foreach(var order in Orders)
foreach(var dispatch in order.Dispatches)
foreach(var dispatchDetail in dispatch.DispatchDetails)
{
// now construct your record object from order.OrderId, order.DateOfOrder, ... , dispatchDetail.Amount
}
For this to work you'll need to construct new Order and Dispatch objects. Also query syntax will make this much easier to read.
Orders = new ObservableCollection<Order>(
from o in orderService.GetAllOrders
from d in o.Dispatches
from dd in d.DispathDetails
select new Order
{
OrderId = o.OrderId,
DateOfOrder = o.DateOfOrder,
PartyName = o.PartyName,
Dispatches = new List<Dispatch>
{
new Dispatch
{
InvoiceNo = d.InvoiceNo
DateOfDispatch = d.DateOfDispatch
DispatchDetails = new List<DispatchDetail> { dd }
}
}
});
Though instead of a collection of Order you might want to just use an anonymous class instead
from o in orderService.GetAllOrders
from d in o.Dispatches
from dd in d.DispathDetails
select new
{
OrderId = o.OrderId,
DateOfOrder = o.DateOfOrder,
PartyName = o.PartyName,
InvoiceNo = d.InvoiceNo
DateOfDispatch = d.DateOfDispatch,
DispatchItemName = dd.ItemName,
DispatchQuantity = dd.Quantity,
DispatchRate = dd.Rate,
DispatchAmount = dd.Amount
}
I have following tables
**Track Table**
+---------------+---------------+--------------------+
| TrackId | TrackName | Path |
+===============+===============+====================+
| 1 | jb | http://domain/1.mp3|
+---------------+---------------+--------------------+
| 2 | remix | http://domain/2.mp3|
+---------------+---------------+--------------------+
**Favorite Table**
+---------------+---------------+--------------------+
| favoriteId | ProfileId | TrackId |
+===============+===============+====================+
| 10 | 2130 | 1 |
+---------------+---------------+--------------------+
| 11 | 2132 | 2 |
+---------------+---------------+--------------------+
I need to select tracks into a model where I have to include a boolean field IsFavorite.
Right now my logic is as follows:
1.Select Tracks
2.Select all favorites by profile
3.Iterate to both list and fill field "IsFavorite"
Is there any better method that can work out the same?
Following is my current logic code
Var ActiveTracks = jukeboxTrackService.GetActiveTracks();
var UserFavorites = jukeboxTrackService.GetFavoritesByProfile(ProfileId);
foreach (var item in ActiveTracks )
{
foreach (var fav in UserFavorites)
{
if (item.JukeBoxTrackId == fav.TrackId)
{
item.IsFavorite = true;
}
}
}
return ActiveTracks ;
Thanks in advance.
(from tr in ActiveTracks
join usrfav in UserFavorites on tr.TrackId equals usr.TrackId into UsrTracks
from usrtr in UsrTracks.DefaultIfEmpty()
select new Track
{
IsFavorite = (usrfav.TrackId == null) ? false : true
}
I have DataTable Like this
Thank you Bob Vale for your help
what is (Select(X,i) mean in your linq,
but as i made a mistake in my table
I have this
No | Size | Type | FB | FP
----------------------------------------
100 | 2 | typeA | FB1 | A1
101 | 3 | typeB | FB1 | A1
101 | 4 | typec | FB1 | A1
103 | 4 | typeC | FB2 | A2
103 | 5 | typeD | FB2 | A2
103 | 6 | typeE | FB2 | A2
I want to have some thing like that
No | Size | Type | FB | FP
---------------------------------
100 | 2 | typeA | FB1 | A1
101 | 3 | typeB | FB1 | A1
| 4 | typec | |
103 | 4 | typeC | FB2 | A2
| 5 | typeD | |
| 6 | typeE | |
How can I make it? I can make Group By
var result = from row in cableDataTable.AsEnumerable()
group row by new
{
FB = row.Field<string>("FB"),
FP = row.Field<string>("FP"),
Size = row.Field<int>("Size"),
Type = row.Field<int>("Type"),
no= row.Field<int>("no"),
} into g
select new
{
FB = g.Key.FB,
FP = g.Key.FP,
Size = g.Key.Size,
Type = g.Key.Type
no= g.Key.no
};
but it that could't give the result
thank you for your attention
How about this:
// First declare a conversion from the DataTable to an anon type
var rows = cableDataTable.AsEnumerable()
.Select(x => new {
Size = x.Field<int>("Size"),
Type= x.Field<string>("Type"),
FB = x.Field<string>("FB"),
FP = x.Field<string>("FP")
});
// Now use group by, ordering and select many to select the rows
var result = rows.GroupBy (row => new {row.FB, row.FP} )
.OrderBy (g => g.Key.FB)
.ThenBy(g => g.Key.FP)
.SelectMany(g => g.OrderBy(row => row.Size)
.Select((x,i) =>
new {
Size = x.Size,
Type = x.Type,
FB = (i==0) ? x.FB : null,
FP= (i==0) ? x.FP : null
}));
You can use linq query as
var result = cableDataTable.AsEnumerable().GroupBy(g => new { g.FB, g.FP}).Select(x => x);