Assign Distinct Object/Class in Linq to objects - c#

I am doing following and it works:
var resultsHeader = (from r in o select new {
OrderID = r.OrderID,
subtotal = r.SubTotal,
city = r.orderAddress.BilltoCity
}).Distinct().ToList();
Look at the city = r.orderAddress.BilltoCity Line, is there any way i can populate the entire object there...like this
var resultsHeader = (from r in o select new {
OrderID = r.OrderID,
subtotal = r.SubTotal,
Address = r.orderAddress
}).Distinct().ToList();
Basicly, I want to store entire OrderAddress Object into Address property, however it does not come out as Distinct object.

You can either use DistinctBy from moreLINQ:
var resultsHeader = (from r in o select new {
OrderID = r.OrderID,
subtotal = r.SubTotal,
city = r.orderAddress.BilltoCity
}).DistinctBy(x => new { x.OrderID, x.subtotal }).ToList();
or GroupBy, which is part of LINQ already:
var resultsHeader = (from r in o
group r by new { r.OrderIs, r.SubTotal } into g
select new {
g.Key.OrderID,
g.Key.SubTotal,
Address = g.First().orderAddress
}).ToList()
UPDATE
Or, you can implement Equals and GetHashCode on your Address class and use Distinct as you do now.

Related

GridView Only populating 1 result

I'm currently working to add Data to a GridView. The data comes from 2 tables that are on different databases. Currently I am able to populate the first entry, but it does not populate past that. here is the code:
void FillOrder(int inv)
{
var _ord = new OrdersContext();
var _pro = new ProductContext();
var qryOrder = (from o in _ord.OrderDetails
where o.InvNumberId == inv
select new
{
o.ProductID,
o.Quantity
}).ToList();
foreach (var order in qryOrder)
{
int prodID = order.ProductID;
int itemCount = qryOrder.Count;
var qryProducts = (from p in _pro.Products
where p.ProductID == prodID
select new
{
p.ProductID,
p.ProductName
}).ToList();
var results = (from t in qryOrder
join s in qryProducts
on t.ProductID equals prodID
select new
{
t.ProductID,
t.Quantity,
s.ProductName
}).ToList();
OrderItemList.DataSource = results;
OrderItemList.DataBind();
}
}
Can anyone help as to why it's only populating the first entry?
If the number of products involved is relatively small, (and since this query seems to be relate to one invoice, I would think that is true), then you can probably use something like the code below.
This is removing the loop, but the contains method will probably generate a SQL statement something like select ProductID, ProductName from products where productID in (,,,,,,) so may fail if the number of parameters is extremely large.
var _ord = new OrdersContext();
var _pro = new ProductContext();
var qryOrder = (from o in _ord.OrderDetails
where o.InvNumberId == inv
select new
{
o.ProductID,
o.Quantity
}).ToList();
// Get the productIDs
var productIDS = qryOrder.Select(o=>o.ProductID).Distinct().ToList();
// Get the details of the products used.
var qryProducts = (from p in _pro.Products
where productIDS.Contains(p.ProductID)
select new
{
p.ProductID,
p.ProductName
}).ToList();
// Combine the two in memory lists
var results = (from t in qryOrder
join s in qryProducts
on t.ProductID equals s.ProductID
select new
{
t.ProductID,
t.Quantity,
s.ProductName
}).ToList();
OrderItemList.DataSource = results;
OrderItemList.DataBind();

Getting a field value from a LINQ query without Iteration

I have the following query in controller and I want to store a column value in a variable but I am not being able to iterate it. Here is my code:
var srmas = (
from SRMAs in db.SRMAs
join SRMAStatus in db.SRMAStatus on SRMAs.Status equals SRMAStatus.Id
join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
where(SRMAs.Id == srmaid)
group SRMADetails by new
{
SRMADetails.Id,
SRMADetails.SRMAId,
SRMADetails.SupplierPartNum,
SRMAs.PONumber,
SRMAs.ActualAmount,
SRMAs.ApprovedOn,
SRMAs.Status,
SRMAs.TrackingNumber,
SRMAs.SupplierRMANumber,
SRMAs.RequestedFromSupp,
SRMAs.CreatedOn,
Suppliers.SupplierName,
SRMAStatus.StatusName,
PurchaseOrders.PODate,
PurchaseOrders.suppliersOrderNumber
} into grp
select new
{
grp.Key.Status,
grp.Key.SRMAId,
grp.Key.Id,
grp.Key.PONumber,
grp.Key.SupplierRMANumber,
grp.Key.ActualAmount,
grp.Key.SupplierPartNum,
grp.Key.RequestedFromSupp,
grp.Key.TrackingNumber,
grp.Key.ApprovedOn,
grp.Key.SupplierName,
grp.Key.StatusName,
grp.Key.PODate,
grp.Key.suppliersOrderNumber,
grp.Key.CreatedOn,
Sum = grp.Sum(SRMADetails => SRMADetails.Cost * SRMADetails.QtyReturned)
}
).ToList();
System.Collections.IEnumerable et = (System.Collections.IEnumerable)srmas;
IEnumerator it = et.GetEnumerator();
while (it.MoveNext())
{
SRMA current = (SRMA)it.Current;
Response.Write(current.Status);
}
ViewBag.SRMAs = srmas.Select(srma => new IndexViewModel
{
Id = srma.SRMAId,
SupplierRMANum = srma.SupplierRMANumber,
SRMADetailsID = srma.Id,
PONumber = srma.PONumber,
CreatedOn = srma.CreatedOn,
SupplierName = srma.SupplierName,
SRMAStatus = srma.StatusName,
Status = srma.Status,
suppliersOrderNumber = srma.suppliersOrderNumber,
PODate = srma.PODate,
Sum = srma.Sum,
TrackingNumber = srma.TrackingNumber,
ActualAmount = srma.ActualAmount
}).ToList();
I just want to get Status value of first record. How do I do it?

C# LINQ: Get count for each row

Here the query for retrieving all the comptes in my base.
I would like to add a number within the object GridCompte in order to count the element inside the list (1,2,3...):
var comptes = (from c in Comptes
join s in Societies on c.IdSoc equals s.IdSoc
select new GridCompte
{
SocCompteId = c.IdCompte,
Name = c.Name,
Nb = ??? COUNT ???,
.....
SocName = s.Name
}).ToList();
I tried using the group statement, but i didn't manage to achieve my goal.
Any suggestions?
First prepare your linq only for the fields you want to get
var comptes = from c in Comptes
join s in Societies on c.IdSoc equals s.IdSoc
select new
{
SocCompteId = c.IdCompte,
Name = c.Name,
.....
SocName = s.Name
};
Now use index option that is available in Select
var finalComptes = (comptes.AsEnumerable()
.Select((comptes, index) => new GridCompte()
{
SocCompteId = c.IdCompte,
Name = c.Name,
Nb = index + 1,
.....
SocName = s.Name
}).ToList();

How to get around Cannot Enumerate More than once using two queries

The below code is throwing a "Cannot Enumerate More Than Once" on the second ToList(). What is the best approach for fixing this error?
var firstQuery = (from r in db.SomeProcedure(Id)
select new MyClass
{
Id = r.Id,
Name = r.Name,
Company= r.Company,
Title = r.Title
});
var secondQuery = (from d in firstQuery
group d by d.Title into groupedTitles
select new MyClass2
{
Title = groupedTitles.Key, //How To include the Id
});
List<MyClass> mClass = firstQuery.ToList();
Th Below ToList() is throwing a cannot enumerate more than one
List<MyClass2> mClass2 = secondQuery.ToList();
How can I fix the error?
Convert your first query to a list right away.
var firstQuery = (from r in db.SomeProcedure(Id)
select new MyClass
{
Id = r.Id,
Name = r.Name,
Company= r.Company,
Title = r.Title
}).ToList();
var secondQuery = (from d in firstQuery
group d by d.Title into groupedTitles
select new MyClass2
{
Title = groupedTitles.Key, //How To include the Id
});
List<MyClass> mClass = firstQuery;
List<MyClass2> mClass2 = secondQuery.ToList();

How to generate SQL COUNT(*) OVER (PARTITION BY {ColumnName}) in LINQ-to-SQL?

Is it possible to generate the following SQL query by using LINQ-to-SQL query expression or method chains which is defer-executable?
Data Structure
alt text http://www.freeimagehosting.net/uploads/e062a48837.jpg
Select Distinct ClassRoomTitle,
Count(*) Over(Partition By ClassRoomNo) As [No Sessions Per Room],
TeacherName,
Count(*) Over(Partition By ClassRoomNo, TeacherName) As [No Sessions Per Teacher] From ClassRoom
Expected Result
alt text http://www.freeimagehosting.net/uploads/47a79fea8b.jpg
Try this:
var vGroup = from p in ClassRoom
group p by new { p.ClassRoomNo, p.TeacherName }
into g
from i in g
select new
{
i.ClassRoomNo,
i.TeacherName,
i.ClassRoomTitle,
NoSessionsPerTeacher = g.Count()
};
var pGroup = from p in vGroup
group p by new { p.ClassRoomNo }
into g
from i in g
select new
{
i.ClassRoomTitle,
NoSessionsPerRoom = g.Count(),
i.TeacherName,
i.NoSessionsPerTeacher
};
var result = pGroup.OrderBy(p => p.ClassRoomNo).ThenBy(p => p.TeacherName);
I didn't test the above but you can check my original code in case I got something wrong in the rewrite:
var vGroup = from p in Products
group p by new { p.ProductId, p.VariantId }
into g
from i in g
select new
{
i.ProductId,
i.VariantId,
VariantCount = g.Count()
};
var pGroup = from p in vGroup
group p by new { p.ProductId }
into g
from i in g
select new
{
i.ProductId,
ProductCount = g.Count(),
i.VariantId,
i.VariantCount
};
var result = pGroup.OrderBy(p => p.ProductId).ThenBy(p => p.VariantId);
var classRooms = from c in context.ClassRooms
group c by new {c.ClassRoomNo} into room
select new {
Title = room.First().ClassRoomTitle,
NoSessions = room.Count(),
Teachers = from cr in room
group cr by new {cr.TeacherName} into t
select new {
Teacher = t.Key,
NoSessions = t.Count()
}
};
A bit more structured than the posted expected result, but I find that to be better.
You can always use SelectMany if you want to go back to unstructured:
var unstructured = classRooms
.SelectMany(c=> c.Teachers.Select( t=> new {
Title = c.Title,
SessionsPerRoom = c.NoSessions,
Teacher = t.Teacher,
SessionsPerTeacher = t.NoSessions
});

Categories

Resources