var getAllProducts = _productService.GetAllProducts();
if (productstest.Count > 0)
{
model.idproduct.Add(new SelectListItem()
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
foreach (var m in getAllProducts)
model.idproduct.Add(new SelectListItem()
{
Value = m.Id.ToString(),
**Text = m.Size.Distinct().ToString(),**
Selected = model.Pid == m.Id
});
}
public virtual IList<Product> GetAllProducts(bool showHidden = false)
{
var query = from p in _productRepository.Table
orderby p.Name
where (showHidden || p.Published) &&
!p.Deleted
select p;
var products = query.ToList();
return products;
}
The issue is even i tried to populate the select list with distinct size using: Text = m.Size.Distinct().ToString(), but it shows the duplicate for instance 100 products are of size 33 cm , the list will populate the dropdownlist in the view with 33cm occuring 100 times , I dont want to show 100 times , just want to show 1 time, Can any one assist me with this issue ?
Presumably you are only trying to show one product of each different size... if so initialising your getAllProducts variable like so will do the trick:
var getAllProducts = _productService.GetAllProducts().GroupBy(p => p.Size).Select(g => g.First());
Related
I have a controller that accepts a list of strings. THese strings essentially are IDs that a user selects on the view. I need to build the model based upon fields from to tables, hence the need for the join. The bellow code will not build as it claims the properties from the joined table do not exist. It only accepts table 1 values. Item.Well_No and Item.Well_Name throw the error. These are included in the "y" table that i joined to "x"..
[HttpPost]
public ActionResult buildSelectionTable(List<string> dta)
{
var a = from x in db._AGREEMENTS
join y in db.WELL_AGMT_XREF on x.AGMT_NUM equals y.AGMT_NUM
where dta.Contains(x.AGMT_NUM)
select x;
List<AgmtModel> model = new List<AgmtModel>();
foreach (var item in a)
{
model.Add(new AgmtModel { Agmt_Name = item.AGMT_NAME, Agmt_Num = item.AGMT_NUM, Agmt_Type = item.AGMT_TYPE_DESCR, Amnt_Status = item.AGMT_STAT_DESCR, Company = item.CO_NAME, DaysToExp = item.DaysToExp, Drs_Url = item.DRS_URL, Effective_Date = item.EFF_DT, Orig_Lessee = item.ORIG_LESSEE, Prop_Status = item.AGMT_PROP_STAT_DESCR, Expiration_Date = item.EXPR_DATE, Acreage = item.LGL_AREA, Extention_Expiration = item.EXTN_EXPR_DT, WellNo = item.WELL_NO, Well_Name = item.WELL_NAME });
}
return PartialView("_SelectionTable", model);
}
You are only selecting x in your query you need to also select y and reference it.
change select x to be select new { x, y}
and then
foreach (var item in a)
{
model.Add(new AgmtModel { Agmt_Name = item.y.AGMT_NAME, Agmt_Num = item.x.AGMT_NUM ... });
}
you need to insert .x or .y before you the field to determine the field names
alternatively you could actually put the constructor directly in the query
so instead of select x
select new AgmtModel { Agmt_Name = y.AGMT_NAME, etc...}
then you can just return PartialView("_SelectionTable", a.ToList())
I use this little piece of code to get the IDs I need, and put them in an array
var userids = from a in db.Person
select a.idlist;
string[] idarray = userids.FirstOrDefault().ToString().Split(';');
How can I use this array of ids to select the matching rows in another query like this
[HttpGet]
public ActionResult GetStuff()
{
var Item = from a in db.Table
where a.id == idarray[0]
and where a.id == idarray[1]
and where a.id == idarray[2]
etc...
select new
{
a.itemid,
a.Element
};
return Json(Item, JsonRequestBehavior.AllowGet);
}
Try something like this:
var Item = from a in db.Table
where idarray.Contains(a.id)
select new
{
a.itemid,
a.Element
};
var Item = from a in db.Table
where idarray.Contains(a.id)
select new
{
a.itemid,
a.Element
}.ToArray();
Don't you want to use Extension Method Lambda syntax? I is same Linq, but just has more code-like view:
var Item = db.Table.Where(x => x.Contains(a.id))
.Select(x => new
{
a.itemid,
a.Element
}).ToArray();
Here's what I usually do.
Get the IDs you need:
var ids = something.Where(s => s.SomeCondition).Select(s => s.Id);
Now Lets get the data based on the Ids:
var response = anothertable.Where(a => ids.Contains(a.Id);
You then can make it a list, array, or whatever you want to do with it. It will go through all the records in anothertable and find the records where the a.Id matches any of the ids.
I'm trying to create a list of orders in a custom Controller in a NopCommerce/MVC application and i want the list to be sorted by creationDate and contain total orders for that date and convert these values to string format.
The thing is i don't want an ActionResult displaying a grid in the view like in Admin/Orders. All i want is a List of all paid orders between model.StartDate and model.EndDate that contains two parameters "CreationDateUtc" and TotalOrders". i simply just need a list containing the data of orders sorted by creationdate.
The if i choose StartDate 2014-03-29 and EndDate 2014-04-02 the output i want would look something like this:
List OrdersTotalList with parameters CreationDateUtc and TotalOrders
CreationDateUtc "2014-03-29"
TotalOrders "562"
CreationDateUtc "2014-03-30"
TotalOrders "485"
CreationDateUtc "2014-03-31"
TotalOrders "733"
CreationDateUtc "2014-04-01"
TotalOrders "729"
CreationDateUtc "2014-04-02"
TotalOrders "681
"
I'm trying to access the data by an implementations of OrderList from OrderController in my CustomController. Problem is this method always returns 10 objects when infact the total number of orders within this timespace is 58. When debugging Total = orders.TotalCount are actually showing 58 orders as one int value). Also a gridmodel is used here but i really don't need a gridmodel, i just need the data from the database:
public List OrderList(GridCommand command, OrderListModel model, OrderModel Omodel)
{
DateTime S = new DateTime(2014, 3, 29); //-- Dates for testing
DateTime E = new DateTime(2014, 4, 02);
model.StartDate = S;
model.EndDate = E;
DateTime? startDateValue = (model.StartDate == null) ? null
: (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.StartDate.Value, _dateTimeHelper.CurrentTimeZone);
DateTime? endDateValue = (model.EndDate == null) ? null
: (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1);
OrderStatus? orderStatus = model.OrderStatusId > 0 ? (OrderStatus?)(model.OrderStatusId) : null;
PaymentStatus? paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)(model.PaymentStatusId) : null;
ShippingStatus? shippingStatus = model.ShippingStatusId > 0 ? (ShippingStatus?)(model.ShippingStatusId) : null;
//load orders
var orders = _orderService.SearchOrders(startDateValue, endDateValue, orderStatus,
paymentStatus, shippingStatus, model.CustomerEmail, model.OrderGuid, command.Page - 1, command.PageSize);
var gridModel = new GridModel<OrderModel>
{
Data = orders.Select(x =>
{
var customerCurrency = _currencyService.GetCurrencyByCode(x.CustomerCurrencyCode);
var totalInCustomerCurrency = _currencyService.ConvertCurrency(x.OrderTotal, x.CurrencyRate);
return new OrderModel()
{
Id = x.Id,
OrderTotal = _priceFormatter.FormatPrice(totalInCustomerCurrency, true, customerCurrency),
OrderStatus = x.OrderStatus.GetLocalizedEnum(_localizationService, _workContext),
PaymentStatus = x.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext),
ShippingStatus = x.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext),
CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc)
};
}),
Total = orders.TotalCount <-- Returns all orders (58) but as an integer
};
var reportSummary = _orderReportService.GetOrderAverageReportLine
(orderStatus, paymentStatus, shippingStatus, startDateValue, endDateValue, model.CustomerEmail);
var profit = _orderReportService.ProfitReport
(orderStatus, paymentStatus, shippingStatus, startDateValue, endDateValue, model.CustomerEmail);
var aggregator = new OrderModel()
{
aggregatorprofit = _priceFormatter.FormatPrice(profit, true, false),
aggregatortax = _priceFormatter.FormatPrice(reportSummary.SumTax, true, false),
aggregatortotal = _priceFormatter.FormatPrice(reportSummary.SumOrders, true, false)
//aggregatordates =
};
List<Order> TotalProductsSold = new List<Order>();
foreach (var o in orders)
{
TotalProductsSold.Add(o);
}
return TotalProductsSold.ToList(); //<-- returns 10 orders containing all order info
}
If i understand correct in order to archive this i have to first search through orders and if their PaymentStatus is Paid. Then create a List in the Method from above. A foreach loop could iterate through orders and add orders to the List, all though i need to specify i only want CreationDate and TotalOrders for that date as parameters in the List.
I know this isn't right but i emagine something similar. The thing is i need a list of order objects and not one object with one value:
List<OrderModel> OrdersTotalList = new List<OrderModel>();
foreach (var o in orders)
{
OrderModel OM = new OrderModel(OM.OrderTotal, OM.CreatedOn);
OrdersTotalList.Add(OM);
}
return OrdersTotalList; //--
Am i completely of or is this the right aproach? I was hoping someone more familiar with NopCommerce knows more about this.
Sorry for all the text
Thank you
Solved.
In order to get a full list of orders you can create a new constructor in IOrderService/OrderService that is of type List instead of IPagedList. The method used for searching orders are called "SearchOrders" and is of type IPagedList. IPagedList contains the property PageSize wich results in only 10 orders.
You can create a new method with same implementation as SearchOrders and change IPagedList to List, remove "int pageIndex" and "int pageSize".
Then use:
_orderService.YourNewConstructor(DateTime? startTime, DateTime? endTime,
OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss, string billingEmail,
string orderGuid)
{
some code...
}
This will give you access to all orders.
How can I do a where in a query on a list or table ?
To explain, I have a multiselect listbox where the user can select one or many values which are passed to my action. After that, I get all this values in a list and I want to do a Where on it like that :
List<string> CondCR = new List<string>();
foreach (var testCR in SubCR)
{
CondCR.Add(testCR);
}
ViewBag.CondCR = CondCR;
var query = (from i in items
where i.Field<String>("TIMING").Contains(GetTIMING) && i.Field<String>("CD_CR").Equals(CondCR)
select new Suivi{CD_CR = i.Field<String>("CD_CR"), CD_APPLI = i.Field<String>("CD_APPLI"), CD_TRT = i.Field<String>("CD_TRT"), LB_TRT = i.Field<String>("LB_TRT"),
PERIODE = i.Field<Int64>("PERIODE"), CD_JOB = i.Field<String>("CD_JOB"), LB_JOB = i.Field<String>("LB_JOB"), CD_TYP_TRT = i.Field<String>("CD_TYP_TRT"),
CD_TRT_SSIS = i.Field<String>("CD_TRT_SSIS"), DT_DEB = i.Field<DateTime>("DT_DEB"), DT_FIN = i.Field<DateTime>("DT_FIN"), DUREE = i.Field<String>("DUREE"),
TIMING = i.Field<String>("TIMING")
}).ToList();
return View(query);
SubCR contains the value that the user select in the list box, SubCR is of type string[].
I've tried to do a where on my list CondCR but it returns nothing and I don't know if it comes from my query or from an other thing.
Have you some suggestions ?
Okay, I've find the answer, I just had to do this in my query :
where CondCR.Contains(i.Field<String>("CD_CR").Trim()) && CondAppli.Contains(i.Field<String>("CD_APPLI").Trim())
I have the following LINQ query to fill up my model.
var blogs = (from b in Context.Blogs
select new BlogTreeView
{
Created = EntityFunctions.TruncateTime(b.Created),
Children = (from ba in Context.Blogs
where EntityFunctions.TruncateTime(ba.Created) == EntityFunctions.TruncateTime(b.Created)
select new BlogTitle
{
ID = ba.ID,
Title = ba.Title
})
}).Distinct();
The problem is that the distinct gives the following error:
"The 'Distinct' operation cannot be applied to the collection ResultType of the specified argument.\r\nParameter name: argument"
I also tried this:
var blogs = (from b in Context.Blogs
select new BlogTreeView
{
Created = EntityFunctions.TruncateTime(b.Created)
}).Distinct();
This gives me only the unique dates like I want.
Then I've tried to add the childrens to the model with the help of a foreach:
foreach (var item in blogs)
{
item.Children = (from ba in Context.Blogs
where
EntityFunctions.TruncateTime(ba.Created) ==
EntityFunctions.TruncateTime(item.Created)
select new BlogTitle
{
ID = ba.ID,
Title = ba.Title
});
}
But then my return value is null for the children list. In my foreach loop the Children list has the values that I want but not in the return field.
What am I doing wrong, and why did the first query gave me that error?