LINQ: adding OrderBy to query - c#

I'm at the finish line for my university project, and I'm kinda stuck at finishing a query.
The working query looks like this:
var Report = from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
};
I would really appreciate it if you can show me, how to Order the results by the given "Quantity" in descending order.
Thanks!

var Report = (from query in Document.Descendants("order")
group query by query.Element("seller").Value into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
})
.OrderByDescending(order => order.Quantity);

Please do this :
var Report = (from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
}).OrderByDescending(x => x.Quantity);
HTH !!!!
(Kudos to LINQ Orderby Descending Query )

The answers by Skippy and Andrei work, but you can also write as
var Report = from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
let qty = qGroup.Sum(p =>int.Parse(p.Element("quantity").Value)).ToString()
orderby qty descending
select new Orders
{
Seller = qGroup.Key,
Quantity = qty
};
if you'd rather keep it all in one syntax.

Related

LINQ - How to group by name from nested array

_id:"63624b321e78f38a3d6baf3e"
Taxes
[0] TaxName:CGST
Amount:9.0
[1] TaxName:SGST
Amount:8.0
_id:"63624b321e78f38a3d6baf3e"
Taxes
[1] TaxName:SGST
Amount:8.0
I need to group by tax name and calculate Total CGST, SGST like below
CGST:9.0
SGST:16.0
I have tried to get the grouping as below. I have an object like movie summary where I added the taxes[] and tried to group by tax name. Please let me know how to do this grouping correctly.
movieSummary.Add(new DSMovieSummaryReport
{
MovieId = orderTicket.MovieId,
Taxes= orderTicket.Taxes,
});
var groupByTaxNamesQuery =
from tax in movieSummary
group tax by tax.Taxes into newGroup
orderby newGroup.Key
select newGroup;
Concept: Flatten array
Flatten the Taxes list to combine all the items from the lists into one list via .SelectMany().
Group by TaxName.
Perform total sum for Amount.
Lastly, with .ToList() to materialize the query execution.
var groupByTaxNamesQuery =
from tax in movieSummary.SelectMany(x => x.Taxes)
group tax by tax.TaxName into newGroup
orderby newGroup.Key
select new { TaxName = newGroup.Key, Amount = newGroup.Sum(x => x.Amount) };
var result = groupByTaxNamesQuery.ToList();
Demo # .NET Fiddle
Thanks to #Svyatoslav Danyliv's suggestion, you can achieve in query expression as below:
var groupByTaxNamesQuery =
from ms in movieSummary
from tax in ms.Taxes
group tax by tax.TaxName into newGroup
orderby newGroup.Key
select new { TaxName = newGroup.Key, Amount = newGroup.Sum(x => x.Amount) };
var result = groupByTaxNamesQuery.ToList();
Demo (Full query expression) # .NET Fiddle
With LINQ i would have done something like :
movieSummary
.SelectMany(m => m.Taxes)
.GroupBy(t=>t.TaxeName)
.Select(g=> new Taxe
{
TaxeName = g.Key,
Amount = g.Sum(t => t.Amount)
});

SQL query in LINQ to SQL

I am trying to write SQL query in LINQ to SQL but after 4h of trying i gave up.
select B.* from Bid B
join
(
select BidId, max(BidVersion) as maxVersion
from Bid
group by BidId
) X on B.BidId = X.BidId and B.BidVersion = X.maxVersion
i saw some tips on the stackOverflow but they werent helpful.
I am using some VERY bad code like:
List<Bid> bidEntities = new List<Bid>();
var newest = from bid in _dbContext.Bids
group bid by bid.BidId into groups
select new { Id = groups.Key, Vs = groups.Max(b => b.BidVersion) };
foreach (var group in newest)
{
bidEntities.Add(await _dbContext.Bids.Where(b => b.BidId == group.Id && b.BidVersion == group.Vs).SingleOrDefaultAsync());
}
Thank you for any advice.
Something like this should work:
var rows = Bids
.GroupBy(b => b.BidId)
.Select(g => g.OrderByDescending(gg => gg.BidVersion).FirstOrDefault())
With LINQ, it helps sometimes not to think in the 'SQL way', but about what you really want. You want the highest version bid for each BidId

LINQ join with top 1 from another table

So the scenario is I have a table of items, and for each item there is a number of comments in another table. I want to get a list of the items with the LATEST comment.
I did this:
var res = (from i in db.Item
select new
{
ID = i.ID,
Name = i.Name,
Comment = (from c in db.Comment
orderby c.Created descending
where c.Item == i.ID
select new { Message = c.Message }).FirstOrDefault().Message
});
Ok, this gets me the results I want, but it's so SLOW... Please, help me make a join out of this instead!
Thank you!
Try this:
var res = db.Item.Join(db.Comment, x=>x.ID, x=>x.ID, (x,y)=>new{x,y})
.OrderByDescending(a=>a.y.Created)
.GroupBy(a=>a.x.ID,(key,items)=>items.First())
.Select(a=> new {
a.x.ID,
a.x.Name,
a.y.Message
});

stuck with a linq query

am stuck with this linq query, all i need is to optimize the last price calculation, cause i get about a 1000 article, & a lot of sales so its getting slow ...
var result = from article in db.Entities.Articles
select new{
article.ID_ART,
article.Designation,
article.BuyPrice,
article.SellPrice,
LastPrice = (from sale in article.Sales where sale.Date == article.Sales.Max(X => X.Date) select sale.Price).FirstOrDefault()==0?
article.BuyPrice: (from sale in article.Sales where sale.Date == article.Sales.Max(X => X.Date) select sale.Price).FirstOrDefault()
}
var result = from article in db.Entities.Articles
let lastPrice = (from sale in article.Sales
orderby sale.Date descending
select sale.Price).FirstOrDefault()
select new
{
article.ID_ART,
article.Designation,
article.BuyPrice,
article.SellPrice,
LastPrice = lastPrice ==0 ? article.BuyPrice : lastPrice
}
You should either join or Include Sales. I assume since it's a navigation property on article that it's an FK table.
Simply use from article in db.Entities.Articles.Include("Sales")... instead.
That will load sales for reference and prevent it from running a subquery when initializing the anonymous type.

Linq query problem

I have a linq query which presents data that is present in CustomersRecord Table as follows. Now I'm grouping the data on invoice number and date of transaction and presenting the data in descending order sorted on Date of Transaction. This is the following query I'm using to achieve that.
(from result in db.CustomersRecords
orderby result.Date_Of_Transaction.Value descending
group result
by new { result.Invoice_Number, result.Date_Of_Transaction } into intermediateResult
select new { InvoiceNumber = intermediateResult.Key.Invoice_Number, DateOfTransaction = intermediateResult.Key.Date_Of_Transaction, TotalAmount = intermediateResult.Sum(result => result.Total_Amount) }).ToList();
But mysteriously I'm getting the data in ascending order, the screen shot is shown here
I don't understand what is happening inside.
Move the order by to after you do your group by
(from result in db.CustomersRecords
group result
by new { result.Invoice_Number, result.Date_Of_Transaction } into intermediateResult
orderby intermediateResult.Key.Date_Of_Transaction descending
select new { InvoiceNumber = intermediateResult.Key.Invoice_Number, DateOfTransaction = intermediateResult.Key.Date_Of_Transaction, TotalAmount = intermediateResult.Sum(result => result.Total_Amount) }).ToList();
The reason why this is so, is because the group by result.Invoice_Number is overriding the previous order by. Since Invoice numbers are usually given in Date order it appears to be in Date Ascending.

Categories

Resources