I am trying to sort a listbox by the customerID and then by Total (discount*unitPrice*quantity) and cannot manage to organize the code in a way that will sort it in that way. Any help would be greatly appreciated.
HERE is a link showing an image on how the results should be returned as.
var load1 = System.IO.File.ReadAllLines(#"c:\temp\AS3Products.csv")
.Select(x => new
{
CID = x.Split(',')[0],
discount = x.Split(',')[2].Trim(),
productId = x.Split(',')[0].Trim()
});
var load2 = System.IO.File.ReadAllLines(#"c:\temp\AS3Transactions.csv")
.Select(x => new
{
productId = x.Split(',')[3],
unitPrice = x.Split(',')[4],
quantity = x.Split(',')[5]
});
var querypractice = from x in load1
join y in load2 on x.productId equals y.productId
where x.CID == "110"
orderby x.discount, y.quantity
select new { x.CID, x.discount, x.productId, y.quantity, y.unitPrice };
foreach (var x in querypractice)
{
double total = double.Parse(x.quantity) * double.Parse(x.unitPrice) * double.Parse(x.discount);
listBox1.Items.Add(x.CID+ " " +x.discount+" "+x.quantity+ " " + total);
}
Disclaimer: I don't have VS on this machine, so this isn't validated, but I think you can do it using the LET statement to set up the calculated value, then order based on it.
var querypractice = from x in load1
join y in load2 on x.productId equals y.productId
let total = x.discount*x.unitPrice*x.quantity
where x.CID == "110"
orderby x.CID, total
select new { x.CID, total };
http://www.codeproject.com/Articles/231164/Into-and-let-in-LINQ-Let-vs-Into
If you're positive that these files have numbers in the expected places all the time, you could parse them as you read them from the files. Otherwise, you'll want to do some validation first or you'll get exceptions.
(I changed double.Parse to decimal.Parse - it's more accurate for manipulating dollar amounts.)
var load1 = System.IO.File.ReadAllLines(#"c:\temp\AS3Products.csv")
.Select(x => new
{
CID = int.Parse(x.Split(',')[0]),
discount = decimal.Parse(x.Split(',')[2].Trim()),
productId = int.Parse(x.Split(',')[0].Trim())
});
var load2 = System.IO.File.ReadAllLines(#"c:\temp\AS3Transactions.csv")
.Select(x => new
{
productId = int.Parse(x.Split(',')[3]),
unitPrice = decimal.Parse(x.Split(',')[4]),
quantity = int.Parse(x.Split(',')[5])
});
Then you can create your list like this. (I removed the specific id you had in your query.)
var orderedList = (from x in load1
join y in load2 on x.productId equals y.productId
let total = (x.discount * y.unitPrice * y.quantity)
orderby x.CID descending, total descending
select new
{
x.CID,
x.discount,
x.productId,
y.quantity,
y.unitPrice
});
Related
it is possible to perform a LINQ like this SQL:
select invoice.credit, ((sum(detailsInvoice.amount) - sum(detailsInvoice.discount))+ sum(detailsInvoice.tax)) as total
from detailsInvoice
join invoice on detailsInvoice.invoiceID = invoice.ID
where invoice.carga = 1428 and invoice.ID <> 0
group by invoice.credit
I'm getting this result in the SQL
I spend so much time trying to create a LINQ to perform that query, without luck.
you should do something like this, please excuse any typo errors, didn't use a compiler to test it.
var result = db.invoice.Include(x=>x.detailsInvoice).
GroupBy(x=>invoice.credit).
Select(y=> new {
credit = y.Key,
Total = (y.Sum(z=>z.detailsInvoice.amount) - y.Sum(z=>z.detailsInvoice.discount) + y.Sum(z=>detailsInvoice.tax))
});
Hope this helps!
your answer gave me a good idea of what to do.
something important I forgot to mention is the Invoice table and detailsInvoice don't have a relationship.
So this is what I did:
var result = (from _invoice in ruterosContext.Invoice
join _details in ruterosContext.DetailsInvoice
on new { id = _invoice.ID, reference = _invoice.Reference } equals
new { id = _details.invoiceID, reference = _details.Reference }
where _invoice.ID != 0 && _invoice.Carga == 1428
select new {
Credit = _invoice.credit,
amount = _details.amount,
discount = _details.discount,
tax = _details.tax
}).GroupBy(x => x.credit).
Select(y => new { Credit = y.Key,
Total = (y.Sum(z => z.amount) - y.Sum(z => z.discount)) + y.Sum(x => x.tax) });
I'm struggling with what is a rather simple SQL select statement. How can this be translated into LINQ?
select
o.IdOrder, Date, s.suma, name, adresa
from
Clients c
join
Orders o on (c.IdClient = o.IdClient)
join
(select IdOrder, sum(price) suma
from OrderProduct
group by IdOrder) s on (o.IdOrder = s.IdOrder);
If you could point me in the right direction, I would greatly appreciate it.
This is what I have so far:
var y = from w in db.OrderProducts
group w by w.IdOrder into TotaledOrder
select new
{
IdOrder = TotaledOrder.Key,
price = TotaledOrder.Sum(s => s.price)
};
var i = 0;
var cc = new dynamic[100];
foreach (var item in y)
{
cc[i++] = db.Orders.Where(t => t.IdOrder == item.IdOrder)
.Select(p => new
{
IdOrder = item.IdOrder,
price = item.price,
}).Single();
}
Your SQL doesn't really give an idea on your underlying structure. By a guess on column names:
var result = from o in db.Orders
select new {
IDOrder = o.IDOrder,
Date = o.Date,
Suma = o.OrderProduct.Sum( op => op.Price),
Name = o.Client.Name,
Adresa = o.Client.Adresa
};
(I have no idea what you meant by the loop in your code.)
In the above diagram for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. I am struggling to create a query for it using linq to sql.
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date.Value.Date,
price1 = g.Sum(x => x.c.price * x.b.quantity) + g.Key.orderLines.Select(o => o.extraPrice).Sum()
});
Given above is linq query I was looking for.
Should be something close to this. I'm not around a computer to test so let me know if you get errors.
db.orders.Select(o => new { o.orderid, o.date, TotalPrice = ( (o.orderLines.Select(ol => ol.food items.Count()).Sum() * o.Quantity) + o.extraPrice) } )
I need to sum elements of same type starting from 2 LINQ queries.
Below is my code:
var query1 = from d in _contextProvider.Context.Documents
where d.TransportId == transportId
group d by d.Type
into dg
select new { DocumentType = dg.Key.ToString(), DocumentCount = dg.Count() };
var query2 = from n in _contextProvider.Context.NotificationDocuments
where n.TransportId == transportId
group n by n.TransportId
into nd
select new { DocumentType = "Notification", DocumentCount = nd.Count() };
var query_collapsed = query1.Union(query2)
.GroupBy(p => new { DocumentType = p.DocumentType })
.Select(g => new DocumentCounters() { DocumentType = g.Key.DocumentType, DocumentCount = g.Sum(p => p.DocumentCount) });
Example: below let's analyse values for DocumentType equals to Notification.
Values of query1:
Values of query2:
The collapsed query :
That's correct: 1 + 2 = 3
The problem: I noticed that whenever the count for Notification in query1 is equals to the count for Notification in query2, then the sum is not performed.
Example:
2 + 2 = 2
or
3 + 3 = 3
Any ideas ?
LINQ Union will remove duplicate entries. If you want to merge the two sequences you can use Concat like so:
var query_collapsed = query1.Concat(query2)
.GroupBy(p => new { DocumentType = p.DocumentType })
.Select(g => new DocumentCounters() { DocumentType = g.Key.DocumentType, DocumentCount = g.Sum(p => p.DocumentCount) });
Actually I want to return the data from different lists based on Date. When i'm using this i'm getting data upto #Var result but i'm unnable to return the data. The issue with this is i'm getting error #return result. I want to return the data #return result. I'm using Linq C#. Can anyone help me out?
public List<CustomerWiseMonthlySalesReportDetails> GetAllCustomerWiseMonthlySalesReportCustomer()
{
var cbsalesreeport = (from cb in db.cashbilldescriptions
join c in db.cashbills on cb.CashbillId equals c.CashbillId
join p in db.products on cb.ProductId equals p.ProductId
select new
{
Productamount = cb.Productamount,
ProductName = p.ProductDescription,
CashbillDate = c.Date
}).AsEnumerable().Select(x => new ASZ.AmoghGases.Model.CustomerWiseMonthlySalesReportDetails
{
Productdescription = x.ProductName,
Alldates = x.CashbillDate,
TotalAmount = x.Productamount
}).ToList();
var invsalesreeport = (from inv in db.invoices
join invd in db.invoicedeliverychallans on inv.InvoiceId equals invd.InvoiceId
select new
{
Productamount = invd.Total,
ProductName = invd.Productdescription,
InvoiceDate = inv.Date
}).AsEnumerable().Select(x => new ASZ.AmoghGases.Model.CustomerWiseMonthlySalesReportDetails
{
Productdescription = x.ProductName,
Alldates = x.InvoiceDate,
TotalAmount = x.Productamount
}).ToList();
var abc = cbsalesreeport.Union(invsalesreeport).ToList();
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription } into grp
select new { Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
**return result;**
}
You can either convert your result to a List before returning it using return result.ToList() or make your method return an IEnumerable<CustomerWiseMonthlySalesReportDetails> instead of List.
As your result is an enumeration of anonymous types you have to convert them to your CustomerWiseMonthlySalesReportDetails-type first:
select new CustomerWiseMonthlySalesReportDetails{ Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
Assuming your type has exactly the members returned by the select.
EDIT: So your code should look like this:
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription } into grp
select new CustomerWiseMonthlySalesReportDetails{ Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
return result.ToList();
You can assume Alldates property if is date of one of groups that month of date is in right place:
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription }
into grp
select new CustomerWiseMonthlySalesReportDetails{
Productdescription = grp.Key.Product,
TotalAmount = grp.Sum(i => i.TotalAmount),
Alldates =grp.First(i=>i.Alldates ) })
.ToList();