My EF query is supposed to be sorting by the date of the first Product in the list, but for some reason, it only sorts most of the products and some of the dates are in the wrong order.
Here's the code...
using (var context = new SalesEntities())
{
var groupedData = context.s84_Schedule.AsExpandable()
.Where(predicate)
.GroupBy(c => new { c.CustomerID, c.s84_Customer.CustomerName, c.SubdivisionID, c.s84_Subdivision.SubdivisionName, c.LotNumber })
.Select(grouped => new s84_Report_Project_POCO
{
CustomerID = grouped.Key.CustomerID,
CustomerName = grouped.Key.CustomerName,
SubdivisionID = grouped.Key.SubdivisionID,
SubdivisionName = grouped.Key.SubdivisionName,
LotNumber = grouped.Key.LotNumber,
Products = grouped.Select(x => new s84_Report_Project_Product
{
ProductID = x.ProductID,
ProductName = x.s84_Product.ProductName,
ProductDate = x.CustomerExpectedDate,
FieldRepID = x.FieldRepID,
FieldRepName = x.s84_FieldRep.FieldRepName,
InstallerID = x.InstallerID,
InstallerName = x.s84_Installer.InstallerName,
StatusID = x.StatusID,
StatusColor = x.s84_Status.StatusColor,
StatusName = x.s84_Status.StatusName,
Completed = x.Completed
}).ToList()
});
var finalList = groupedData.ToList().Where(x => x.Products.Last().Completed == false).ToList();
List<s84_Report_Project_POCO> lst = finalList.OrderBy(x => x.Products.First().ProductDate).ToList();
return lst;
}
Code seems good to me, but look at how one of the dates is out of order...
weird sorting http://www.84sales.com/weird_sort.png
Try doing the order by on the inital select
var groupedData = context.s84_Schedule.AsExpandable()
.Where(predicate)
.GroupBy(c => new { c.CustomerID,
c.s84_Customer.CustomerName,
c.SubdivisionID,
c.s84_Subdivision.SubdivisionName,
c.LotNumber })
.Select(grouped => new s84_Report_Project_POCO
{
CustomerID = grouped.Key.CustomerID,
CustomerName = grouped.Key.CustomerName,
SubdivisionID = grouped.Key.SubdivisionID,
SubdivisionName = grouped.Key.SubdivisionName,
LotNumber = grouped.Key.LotNumber,
Products = grouped
.Select(x => new s84_Report_Project_Product
{
ProductID = x.ProductID,
ProductName = x.s84_Product.ProductName,
ProductDate = x.CustomerExpectedDate,
FieldRepID = x.FieldRepID,
FieldRepName = x.s84_FieldRep.FieldRepName,
InstallerID = x.InstallerID,
InstallerName = x.s84_Installer.InstallerName,
StatusID = x.StatusID,
StatusColor = x.s84_Status.StatusColor,
StatusName = x.s84_Status.StatusName,
Completed = x.Completed
}).OrderBy(x => x.CustomerExpectedDate).ToList()
});
The problem is the .First() function, witch returns the first record, but not necessarly in date order. if you wich to order your grouped datas by date so that the First() function returns the most recent date, you'll need to order your datas before grouping them, and then REorder your results with the First()function :
using (var context = PrimaryConnection.returnNewConnection())
{
var groupedData = context.s84_Schedule.AsExpandable()
.Where(predicate)
.GroupBy(c => new { c.CustomerID, c.s84_Customer.CustomerName, c.SubdivisionID, c.s84_Subdivision.SubdivisionName, c.LotNumber })
.Select(grouped => new s84_Report_Project_POCO
{
CustomerID = grouped.Key.CustomerID,
CustomerName = grouped.Key.CustomerName,
SubdivisionID = grouped.Key.SubdivisionID,
SubdivisionName = grouped.Key.SubdivisionName,
LotNumber = grouped.Key.LotNumber,
Products = grouped
.Select(x => new s84_Report_Project_Product
{
ProductID = x.ProductID,
ProductName = x.s84_Product.ProductName,
ProductDate = x.CustomerExpectedDate,
FieldRepID = x.FieldRepID,
FieldRepName = x.s84_FieldRep.FieldRepName,
InstallerID = x.InstallerID,
InstallerName = x.s84_Installer.InstallerName,
StatusID = x.StatusID,
StatusColor = x.s84_Status.StatusColor,
StatusName = x.s84_Status.StatusName,
Completed = x.Completed
}).Orderby(t => t.CustomerExpectedDate).ToList()
});
var finalList = groupedData.ToList().Where(x => x.Products.Last().Completed == false).ToList();
List<s84_Report_Project_POCO> lst = finalList.OrderBy(x => x.Products.First().ProductDate).ToList();
All SQL queries (and hence Linq queries, when attached to a SQL database) have a random order, unless you sort them.
Products is not sorted - hence it has a random order.
You sort by Products.First(), but Products has a random order, so your sort will also be random.
Make sure Products is sorted within the query, and you should be ok.
Products = grouped.Select(....)
.OrderBy(x => x.ProductDate)
.ToList()
Related
I'm reading a CSV file splitting it into cols, then grouping into a new class.
It looks clunky just wondering is there is a more simple method for instance like not selecting them into the class first:
EDIT: so to clarify I'm trying to get the TimesheetHours grouped by all the other columns.
var rowList = csvFile.Rows.Select(row => row.Split(','))
.Select(cols => new UtilisationRow {
UploadId = savedUpload.Id,
FullName = cols[0],
TimesheetWorkDateMonthYear = Convert.ToDateTime(cols[1]),
TimesheetTaskJobnumber = cols[2],
TimesheetWorktype = cols[3],
TimesheetHours = Convert.ToDouble(cols[4]),
TimesheetOverhead = cols[5]
})
.GroupBy(d => new {
d.FullName,
d.TimesheetWorkDateMonthYear,
d.TimesheetTaskJobnumber,
d.TimesheetWorktype,
d.TimesheetOverhead
})
.Select(g => new UtilisationRow {
FullName = g.First().FullName,
TimesheetWorkDateMonthYear = g.First().TimesheetWorkDateMonthYear,
TimesheetTaskJobnumber = g.First().TimesheetTaskJobnumber,
TimesheetWorktype = g.First().TimesheetWorktype,
TimesheetHours = g.Sum(s => s.TimesheetHours),
TimesheetOverhead = g.First().TimesheetOverhead
})
.ToList();
Many thanks,
Lee.
The two problems in your code are that you call First() repeatedly on a group, while you should retrieve that same data from group's key, and that you are using UtilisationRow in the first Select, which should use an anonymous type instead:
var rowList = csvFile.Rows.Select(row => row.Split(','))
.Select(cols => new {
UploadId = savedUpload.Id,
FullName = cols[0],
TimesheetWorkDateMonthYear = Convert.ToDateTime(cols[1]),
TimesheetTaskJobnumber = cols[2],
TimesheetWorktype = cols[3],
TimesheetHours = Convert.ToDouble(cols[4]),
TimesheetOverhead = cols[5]
})
.GroupBy(d => new {
d.FullName,
d.TimesheetWorkDateMonthYear,
d.TimesheetTaskJobnumber,
d.TimesheetWorktype,
d.TimesheetOverhead
})
.Select(g => new UtilisationRow {
FullName = g.Key.FullName,
TimesheetWorkDateMonthYear = g.Key.TimesheetWorkDateMonthYear,
TimesheetTaskJobnumber = g.Key.TimesheetTaskJobnumber,
TimesheetWorktype = g.Key.TimesheetWorktype,
TimesheetHours = g.Sum(s => s.TimesheetHours),
TimesheetOverhead = g.Key.TimesheetOverhead
})
.ToList();
Now the "pipeline" of your method looks pretty clean:
The first Select does the initial parsing into a temporary record
GroupBy bundles matching records into a group
The final Select produces records of the required type.
I have two lists of same type with different key value pairs,
List1 has "isPermanent = true" and List2 has false value and also
List1 has an extra key "nextVacationDate".
Im trying to do union of these as below but im afraid I will still get the duplicates because of different values. I need to merge both lists in to one list and order by List1 first (Permanent employees first)..is there a better way to do this using LINQ?
public newList1 List1(string abcd)
{
var result = serviceMethod1(abcd);
var newList1 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = true,
nextVacationDate =x.VacDt,
salary = x.Bsalary
}));
return newList1;
}
public newList2 List2(string defg)
{
var result = serviceMethod2(defg);
var newList2 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = false,
salary = x.Bsalary
}));
return newList2;
}
private List<emp> EmployyeList(List<emp> newList1, List<emp> newList2)
{
var sortedEmpList1 = newList1.OrderBy(i => i.Fname);
var sortedEmpList2 = newList2.OrderBy(i => i.Fname);
List<MeterModel> combinedList = newList1.Union(newList2) as List<emp>;
return combinedList;
}
You can filter the 2nd list to avoid duplicates:
newList1.Union(newList2.Where(emp2 => !newList1.Any(emp1 => emp1.employeeId == emp2.employeeId)))
I want list of all unique Scheme_Codes but I am unable to write query. I tried this one but I am confused what's problem with this query.
var queryresult = db.MFData.GroupBy(x => new { Scheme_Name = x.Scheme_Name, Scheme_Code = x.Scheme_Code, FundFamily = x.FundFamily, Date = x.Date })
.Select(group => new
{
Scheme_name = group.Key.Scheme_Name,
Scheme_Code = group.Key.Scheme_Code,
FundFamily = group.Key.FundFamily,
Date = group.Max(x => x.Date),
count = group.Select( x => x.Scheme_Code).Distinct().Count()
}
).OrderBy(x => x.Scheme_Code);
I have this query but I am not sure how to convert this to linq
SELECT [Scheme_Code],[FundFamily],[Scheme_Name],
MAX([Date]) as LastDate
FROM [MFD].[dbo].[MFDatas]
GROUP BY [Scheme_Code],[Scheme_Name], [FundFamily]
ORDER BY [Scheme_Code]
All you have to do is omit the date from your groupby-clause:
var queryresult = db.MFData.GroupBy(x => new
{
Scheme_Name = x.Scheme_Name,
Scheme_Code = x.Scheme_Code,
FundFamily = x.FundFamily
}).Select(group => new
{
Scheme_name = group.Key.Scheme_Name,
Scheme_Code = group.Key.Scheme_Code,
FundFamily = group.Key.FundFamily,
Date = group.Max(x => x.Date),
count = group.Select(x => x.Scheme_Code).Distinct().Count()
}).OrderBy(x => x.Scheme_Code);
var list = dc.Orders.
Join(dc.Order_Details,
o => o.OrderID, od => od.OrderID, <-- what if i have 2 more parameters let say an ID and a REC on both table. ex.: o=> o.OrderID && o.ItemName, od => od.OrderID && od.Itemname then (o, od) but its result is error? is there another way?
(o, od) => new
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
ShipName = o.ShipName,
Quantity = od.Quantity,
UnitPrice = od.UnitPrice,
ProductID = od.ProductID
}).Join(dc.Products,
a => a.ProductID, p => p.ProductID, <-- at this point too?
(a, p) => new
{
OrderID = a.OrderID,
OrderDate = a.OrderDate,
ShipName = a.ShipName,
Quantity = a.Quantity,
UnitPrice = a.UnitPrice,
ProductName = p.ProductName
});
is it possible to use this lambda expression linq query with multiple parameters by joining 3 tables?
--- UPDATE STILL ERROR -- :(
var header = DB.Delivery_HeaderRECs.Join(DB.Delivery_DetailsRECs, <-- Red Line on DB.Delivery_HeaderRECs.Join
q => new { q.drNO, q.RecNO },
qw => new { qw.DrNO, qw.RecNO },
(q, qw) => new
{
DR = q.drNO,
DATE = q.DocDate,
RECNO = q.RecNO,
CUSTID = q.CustomerID,
CUSTADDR = q.CustomerADDR,
RELEASE = q.ReleasedBy,
RECEIVE = q.ReceivedBy,
REMARKS = q.Remarks,
ITEM = qw.ItemCode,
DESC = qw.ItemDesc,
QTY = qw.Qty,
COST = qw.Unit,
PLATENO = qw.PlateNo,
TICKETNO = qw.TicketNo
}).Join(DB.Delivery_TruckScaleRECs,
w => new { w.DR, w.TICKETNO },
we => new { we.DrNo, we.TicketNO },
(w, we) => new
{
DR = w.DR,
DATE = w.DATE,
RECNO = w.RECNO,
CUSTID = w.CUSTID,
CUSTADDR = w.CUSTADDR,
RELEASE = w.RELEASE,
RECEIVE = w.RECEIVE,
REMARKS = w.REMARKS,
ITEM = w.ITEM,
DESC = w.DESC,
QTY = w.QTY,
COST = w.COST,
PLATENO = w.PLATENO,
TICKETNO = w.TICKETNO,
TRANSAC = we.TransactionType,
FWEIGHT = we.FirstWeight,
SWEIGHT = we.SecondWeight,
NWEIGHT = we.NetWeight
}).FirstOrDefault();
I made up changes base on the answer but an error said above the statement:
"The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly". i think it's talking about the parameters i've made..
You can use anonymous type for the Join like this:
var list = dc.Orders.Join(dc.Order_Details,
o => new { o.OrderID, o.ItemName},
od => new { od.OrderID, od.ItemName},
...);
The anonymous type will be compiled to use the autoimplemented Equals and GetHashCode so that the equality will be derived by the equality of all the corresponding properties. Just add more properties as you want in the the new {....}. Note that the order of properties provided in the 2 new {...} should be the same order of correspondence. The names should also be matched, you can explicitly specify the names to ensure this (this is needed in some cases) such as:
new {OrderID = o.OrderID, Name = o.ItemName}
However in your case the property names will be used as the same properties of the item.
UPDATE
This update is just a fix for your specific parameters, I said that the property names should be the same, if they are not you have to explicitly name them like this:
var list = dc.Orders.Join(dc.Order_Details,
q => new {DrNO = q.drNO, q.RecNO},
qw => new {DrNO = qw.DrNO, qw.RecNO},
...);
This is the data in my database table:
That's my business object:
public class Unit
{
public Unit()
{
MemberIdList = new List<String>();
}
public String UnitType { get; set; }
public String UnitZoom { get; set; }
public String MemberZoom { get; set; }
public List<String> MemberIdList { get; set; }
}
The whole data from database is fetched and put into a DataTable.
Now comes the Linq Transformation...
After I return a List with 3 Unit objects holding this data:
Now guess how I got the data into the 3 business objects...
that's the way I would like to know. A hint might be Distinct and IEqualityComparer for the 3 properties...
just an assumption...
UPDATE
Question updated:
Please read the comment in the code :)
var groupedCollection = table.AsEnumerable()
.GroupBy(row => new
{
UType = row.Field<string>("UnitType"),
UZoom = row.Field<string>("UnitZoom"),
MZoom = row.Field<string>("MemberZoom"),
MOrder = row.Field<int>("MemberOrder"),
// I DO NOT WANT the MemberOrder to be in the Group Key, but later on I use this Property to order by it...
});
var unitCollection = groupedCollection
.Select(g => new Unit
{
UnitType = g.Key.UType,
UnitZoom = g.Key.UZoom,
MemberZoom = g.Key.MZoom,
MemberIdList = g.Select(r => r.Field<string>("MemberId")).OrderBy(b => g.Key.MOrder).ToList(),
});
List<Unit> units = unitCollection.ToList();
This is how I would do it:
var values = TblMembers.ToList();
var lst =
(from m in values
group m by new { m.UnitType, m.UnitZoom, m.MemberZoom } into g
select new
{
g.Key.UnitType,
g.Key.UnitZoom,
g.Key.MemberZoom,
MemberIdList = g.Select (x => x.MemberID).ToList()
}).ToList();
Something like this ?
DataTable dt = ...
var list =
dt.AsEnumerable()
.GroupBy(r => new
{
UType = r.Field<string>("UnitType"),
UZoom = r.Field<string>("UnitZoom"),
MZoom = r.Field<string>("MemberZoom")
})
.Select(g => new Unit
{
UnitType = g.Key.UType,
UnitZoom = g.Key.UZoom,
MemberZoom = g.Key.MZoom ,
MemberIdList = g.Select(r => r.Field<string>("MemberId")).Distinct().ToList()
})
.ToList();
EDIT:
the call to .Distinct() is not strictly necessary. It avoids duplicated MemberIds if you can have them, but it really depends on what OP needs.
EDIT2:
(according to the last question update)
You are close to the solution:
just change this line of my code:
MemberIdList = g.Select(r => r.Field<string>("MemberId")).ToList()
to:
MemberIdList = g.Select(r => r.Field<string>("MemberId")).OrderBy(r => r.Field<int>("MOrder")).ToList()
var result =
from n in data
group n by new { n.UnitType, n.UnitZoom, n.MemberZoom } into g
select new Unit
{
UnitType = g.Key.UnitType,
UnitZoom = g.Key.UnitZoom,
MemberZoom = g.Key.MemberZoom ,
MemberIdList = g.Select ( r => r.MemberId).ToList()
};