How to group with a written specified DataContextClass? - c#

I want to group dvdlist by categoryid, Similar to this, but no DVDDataContext
This one works,
DvdDataContext db = new DvdDataContext();
var q = from b in db.DvdLists
group b by b.CategoryId into g
select new { CategoryID = g.Key, DvdLists = g };
I need the following kind of code, but the error occurs at GetTable()=g
DataContext db = new DataContext(conString);
var dvd = db.GetTable<DvdList>();
var query = from b in dvd
group b by b.CategoryId into g
select new { CategoryId = g.Key, GetTable<DvdList>()= g };

You cannot specify GetTable() in anonymous types. Try { CategoryId = g.Key, GetTable= g };
Hope it helps!

Related

LINQ Group By Join

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

Returning List value using linq C#

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

Adding more items to a group by statement

I have this query:
var rowsPerProvider = (from row in dt.Select()
let emp = row["f_name"].ToString().Trim()
group row by emp
into g
select g).ToDictionary(
g => g.Key,
g => g.ToArray());
How can I update it to also filter on some more columns? for example currently it is on f_name. How can I update it to group on f_name and m_name and l_name?
Make an anonymous object containing the fields you want to group by:
var rowsPerProvider = (from row in dt.Select()
group row by new
{
emp1 = row["f_name"].ToString().Trim(),
emp2 = row["m_name"].ToString().Trim(),
emp3 = row["l_name"].ToString().Trim(),
}
into g
select g).ToDictionary(
g => g.Key,
g => g.ToArray());
Use anonymous class:
// (...)
group row by new { emp, something }

LINQ - Left join and Group by and Sum

I have two lists                                                      
var stores = new[]
{
new { Code = 1, Name = "Store 1" },
new { Code = 2, Name = "Store 2" }
};
var orders = new[]
{
new { Code = 1, StoreCode = 1, TotalValue = 14.12 },
new { Code = 2, StoreCode = 1, TotalValue = 24.12 }
};
OUTPUT
StoreName = Store 1 | TotalValue = 38.24
StoreName = Store 2 | TotalValue = 0
How can I translate this into LINQ to SQL?                                             
var lj = (from s in stores
join o in orders on s.Code equals o.StoreCode into joined
from j in joined.DefaultIfEmpty()
group s by new
{
StoreCode = s.Code,
StoreName = s.Name
}
into grp
select new
{
StoreName = grp.Key.StoreName,
TotalValue = ???
}).ToList();
When you doing group join, all orders related to store will be in group, and you will have access to store object. So, simply use s.Name to get name of store, and g.Sum() to calculate total of orders:
var lj = (from s in db.stores
join o in db.orders on s.Code equals o.StoreCode into g
select new {
StoreCode = s.Name,
TotalValue = g.Sum(x => x.TotalValue)
}).ToList();
Note - from your sample it looks like you don't need to group by store name and code, because code looks like primary key and it's unlikely you will have several stores with same primary key but different names.

LINQ group by expression syntax

I've got a T-SQL query similar to this:
SELECT r_id, r_name, count(*)
FROM RoomBindings
GROUP BY r_id, r_name
I would like to do the same using LINQ. So far I got here:
var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by roomBinding.R_ID into g
select new { ID = g.Key };
How can I extract the count(*) and r_name part?
Try this:
var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by new
{
Id = roomBinding.R_ID,
Name = roomBinding.r_name
}
into g
select new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
};
Edit by Nick - Added method chain syntax for comparison
var rooms = roomBinding.GroupBy(g => new { Id = g.R_ID, Name = g.r_name })
.Select(g => new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
});

Categories