Linq query, how to orderby - asp.net-mvc

I have a method that gets some data from the database by some linq queries. The data is shown as expected but not in the order I wan't. I need to sort the products I get from the database by the TotalQuantity property shown in query 1 and 2. Im trying to use OrdeBy but I'm not sure how to add it in this context. Need some help with this one.
This is my method:
public IList<BestsellersReportLine> DailyBestsellersReport()
{
OrderStatus os;
PaymentStatus ps;
ShippingStatus ss;
int billingCountryId = 0;
int recordsToReturn = 10;
int orderBy = 1;
int groupBy = 1;
var range = new
{
startTimeUtc = DateTime.Today.AddDays(-1),
endTimeUtc = DateTime.Today.AddSeconds(-1),
CreatedOnUtc = DateTime.Today.AddDays(-1),
};
var query1 = from opv in _opvRepository.Table
join o in _orderRepository.Table on opv.OrderId equals o.Id
join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
join p in _productRepository.Table on pv.ProductId equals p.Id
where (o.CreatedOnUtc >= range.startTimeUtc && o.CreatedOnUtc <= range.endTimeUtc)
select opv;
var query2 = groupBy == 1 ?
//group by product variants
from opv in query1
group opv by opv.ProductVariantId into g
select new
{
EntityId = g.Key,
TotalAmount = g.Sum(x => x.PriceExclTax),
TotalQuantity = g.Sum(x => x.Quantity),
}
:
//group by products
from opv in query1
group opv by opv.ProductVariant.ProductId into g
select new
{
EntityId = g.Key,
TotalAmount = g.Sum(x => x.PriceExclTax),
TotalQuantity = g.Sum(x => x.Quantity),
};
switch (orderBy)
{
case 1:
{
query2 = query2.OrderByDescending(x => x.TotalQuantity);
}
break;
case 2:
{
query2 = query2.OrderByDescending(x => x.TotalAmount);
}
break;
default:
throw new ArgumentException("Wrong orderBy parameter", "orderBy");
}
if (recordsToReturn != 0 && recordsToReturn != int.MaxValue)
query2 = query2.Take(recordsToReturn);
var result = query2.ToList().Select(x =>
{
var reportLine = new BestsellersReportLine()
{
EntityId = x.EntityId,
TotalAmount = x.TotalAmount,
TotalQuantity = x.TotalQuantity
};
return reportLine;
}).ToList();
return result;
}

What about return
result.OrderBy(x => x.totalQuantity).ToList();
Update:
I can only think of adding .ToList() to the end again.

Remove the first ToList() after query2 as mentioned below:
var result = query2.Select(x =>
{
var reportLine = new BestsellersReportLine()
{
EntityId = x.EntityId,
TotalAmount = x.TotalAmount,
TotalQuantity = x.TotalQuantity
};
return reportLine;
}).ToList();

Related

GROUP BY LINQ ASP.NET MVC

Let's suppose we have a Linq query like this:
int companyID = Convert.ToInt32(((UserIdentity)User.Identity).CompanyId);
var stock = from i in _stockService.GetStock()
join ur in _inventoryService.GetInventory() on i.ProductID equals ur.Id
where ur.ComapnyId == companyID
select new StockVM
{
Product = ur.ItemName,
Quantity = i.Quantity,
BatchID = i.BatchID,
StockStatus = i.StockStatus,
MfgDate = i.MfgDate,
ExpDate = i.ExpDate,
};
Result
How to do a "Group By Product" with sum of Quantity in this linq query?
I need to only get max ExpDate firstOrDefault
try something like this:
int companyID = Convert.ToInt32(((UserIdentity)User.Identity).CompanyId);
var stock = from i in _stockService.GetStock()
join ur in _inventoryService.GetInventory() on i.ProductID equals ur.Id
where ur.ComapnyId == companyID
group new { Quantity = i.Quantity } by new { ur.ItemName } into g
select new { Product = g.Key, TotalQuantity = g.Sum() } ).ToList() ;
List<StockVM> _lst = new List<StockVM>();
foreach(var item in stock ){
StockVM row = new StockVM();
row.Product = item.ItemName;
//....
_lst.Add(row);
}

Linq Query to fetch data using non entity object

I'm trying to fetch the record from 3 tables by comparing the user Logged in name
Here is my code:
public ActionResult MeritList() //departmental merit listed students details with status 1
{
var username= HttpContext.Session["UserName"];
List<StdListModel> model = new List<StdListModel>();
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
//join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && e.tblDepartment.DepartName == username
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
foreach(var item in query)
{
model.Add(new StdListModel()
{
ID=item.ID,
Name=item.Name,
FatherName=item.FatherName,
CNIC=item.CNIC,
FormNo=item.FormNo,
DiaryNo=item.DiaryNo
});
}
return View(model);
}
Also Tried this Query
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && d.DepartName.Equals(username)
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
But it does not return anything model=0, query =0, the database has right values and I don't get any error either.
please check username with tolower() and trim function.
e.tblDepartment.DepartName.ToLower().Trim() == username.ToLower().Trim()
or
e.tblDepartment.DepartName.ToLower().Trim().equals(username.ToLower().Trim())
I got the problem. It is in
s.Status == '1'
I just changed it into
s.Status == 1
and it works fetch the data from the database.

Apply Groupby in EF with suitable results

I am not much familiar with EF. I want to group rows based on IDs. I acheive this in SQL but I am getting some Issues with group by while implementeing in EF.
public ActionResult PropertyListing()
{
if (Session["UserID"] == null)
{
return RedirectToAction("Login", "Property");
}
return View();
}
public JsonResult GetSpurts()
{
PropertySpurts property;
List<PropertySpurts> listProperty = new List<PropertySpurts>();
var userID = Convert.ToInt32(Session["UserID"].ToString());
// IEnumerable<tblPropertyView> PropertyList;
var PropertyList = from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.PropertyID into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t => t.ID != null) };
if (PropertyList != null)
{
foreach (var item in PropertyList)
{
property = new PropertySpurts();
property.ID = (int)item.ParentId;
property.Title = item.tblProperty.Title;
listProperty.Add(property);
}
}
return Json(listProperty, JsonRequestBehavior.AllowGet);
}
PropertyID in tblPropertyView is Foreign Key to tblProperty ID. I want to get title of Property from tblProperty. Please help me to find Title and Count of PropertyViews
TIA
[SOLVED]
var PropertyList = from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by new
{
p.PropertyID,
p.tblProperty.Title
} into grouped
select new
{
ParentId = grouped.Key.PropertyID,
Title = grouped.Key.Title,
Count = grouped.Count(t => t.ID != null)
};
This solves my issue. But I want this should be orderby count.
var PropertyList = (from p in dbEntity.tblPropertyViews
join c in dbEntity.tblProperties on p.PropertyID equals c.ID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by new
{
p.PropertyID,
p.tblProperty.Title
} into grouped
select new
{
ParentId = grouped.Key.PropertyID,
Title = grouped.Key.Title,
Count = grouped.Count(t => t.ID != null)
}).OrderByDescending(x => x.Count);

LINQ Join with where condition

I can use LINQ's Join with Lambda notations no problem, but I can't work out how one would then add a where condition.
var q = query.Join(context.CustomerIds,
x => x.CustomerId,
y => y.CustomerId,
(x, y) => new CustomerLookupResult()
{
dob = x.DateOfBirth.ToString(),
forenames = x.Forenames,
surname = x.Surname,
loyaltyNo = y.Identifier,
customerId = x.CustomerId
});
The table I'm joining the first to contains the loyaltyNo in its Identifier column, but also contains other information in the same column and so uses a second column IdentifierTypeCode to allow filtering.
So how do I now add .Where(x => x.IdentifierTypeCode == "LOYALTY") like I would in SQL. Appending this to end refers to the new object.
You could apply your Where before doing the join.
var q = customerLoyalties
.Where(x => x.IdentifierTypeCode == "LOYALTY")
.Join(customers,
x => x.CustomerId,
y => y.CustomerId,
(x, y) => new CustomerLookupResult()
{
CustomerId = y.CustomerId,
Name = y.Name,
IdentifierTypeCode = x.IdentifierTypeCode
});
You can also use this way to achieve that using Linq.
var match = from t1 in context.orders
join t2 in context.orderdetails on
new { t1.OrderID } equals
new { t2.OrderID }
join t3 in context.products on
new { t2.ProductID } equals
new { t3.ProductID }
where t3.ProductID == id
select t3;
return match.ToList();
The first parameter to the Join takes any IEnumerable, so you can apply the Where at that point, or earlier
var q = query.Join(context.CustomerIds.Where(x=>x.IdentifierTypeCode=="LOYALTY"),
x => x.CustomerId,
y => y.CustomerId,
(x, y) => new CustomerLookupResult()
{
dob = x.DateOfBirth.ToString(),
forenames = x.Forenames,
surname = x.Surname,
loyaltyNo = y.Identifier,
customerId = x.CustomerId
});
alternatively, if you don't like to put too much on one line:
var filteredLoyalties = context.CustomerIds.Where(x=>x.IdentifierTypeCode=="LOYALTY");
var q = query.Join(filteredLoyalties,
...

How to write if condition inside where clause in linq

I want to write if condition inside where clause. because if first name or last name is null I don't wani to add it in where clause . other wise I want to add it.
so I write
var query1 = from opv in _opvRepository.Table
join o in _orderRepository.Table on opv.OrderId equals o.Id
join gr in _graduandRepository.Table on opv.graduand_id equals gr.graduand_id
join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
join p in _productRepository.Table on pv.ProductId equals p.Id
where (opv.ceremony_id == ceremony_id) &&
(!o.Deleted) && (opv.IsHireItem == true) &&
(!p.Deleted) &&
(!pv.Deleted) && (opv.ceremony_id == ceremony_id)
// group opv by opv.OrderId into g
select new
{
opvTable = opv,
grTable = gr,
};
// This is not working. I have problem in here. How to add this??
if (!String.IsNullOrEmpty(Fname))
query1 = query1.Where(grTable = > grTable.first_name == Fname);
var result = query1.ToList().Select(x =>
{
return new HireItemReportLine()
{
OrderId = x.opvTable.OrderId,
OrderDate=x.opvTable.Order.CreatedOnUtc,
Amount= x.opvTable.Order.OrderSubtotalExclTax,
PaymentMethod = x.opvTable.Order.PaymentMethodSystemName,
paidDate = x.opvTable.Order.CreatedOnUtc,
Fname = x.grTable.first_name,
MName = x.grTable.middle_name,
LName = x.grTable.last_name,
};
}).ToList();
What is the wrong with my cording??
Note that your original query selects an anonymous type with two properties: opvTable and grTable. So, you need to use one of those properties in the subsequent Where clause, like this:
query1 = query1.Where(item => item.grTable.first_name == Fname);

Resources