I'm creating a linq query in which I need to return minimum and maximum values of the years and prices of cars.
Linqpad:
var result = (from c in Cars
where c.IsShowed == true
c.CarCod == carCod
group c by c.CarCod into cg
select new {
MinPrice = cg.Min(cv => cv.Price) ,
MaxPrice = cg.Max(cv => cv.Price),
MinYear = cg.Min(cv => cv.Year),
MaxYear = cg.Max(cv => cv.Year)
})
.SingleOrDefault();
result.Dump();
How would I return a default value, example 0, for all properties MinPrice, MaxPrice, MinYear, MaxYear if the query is empty.
You should declare intermediate Result class for that:
var result = (from c in Cars
where c.IsShowed && c.CarCod == carCod
group c by c.CarCod into cg
select new Result {
MinPrice = cg.Min(cv => cv.Price) ,
MaxPrice = cg.Max(cv => cv.Price),
MinYear = cg.Min(cv => cv.Year),
MaxYear = cg.Max(cv => cv.Year)
})
.SingleOrDefault() ?? new Result();
Related
I am new to lambda exp. I have created a linq statement but I 'm not aware how to convert my code into lambda exp.
var result = (from order1 in Orders
join packedorder1 in VracExcluded on order1.codOrder equals packedorder1.codOrder
join product1 in Products on order1.codProduct equals product1.codProduct
join packedproduct1 in PackedProducts on packedorder1.codPackedProduct equals packedproduct1.codPackedProduct
where order1.codOrder == _order.codOrder
select new FinishedProductPrintingM
{
OF = order1.codOrder,
Item = "0",
Ligne = packedorder1.codLine,
Material = packedorder1.codPackedProduct,
Produit = product1.codProductType,
MaterialDescription = packedproduct1.lblPackedProduct,
Lot = packedorder1.codPackedBatch,
RéférenceClient = product1.codCustomerColor,
Quantité = packedorder1.nbrPackedQuantity.ToString(),
Déjàimprimé = packedorder1.nbrLabelPrinted
}).ToList();
Can anyone help me to understand, how can I create a lambda exp of my linq query?
Is is always useful to use msdn if you are not aware about how to use .net APIs.
var result = Orders.Join(VracExcluded, o => o.codOrder, v => v. codOrder, (o, v) => new { Order = o, VracExcluded = v })
.Join(Products, x => x.Order.codProduct, p => p.codProduct, (x, p) => new { Order = x.Order, VracExcluded = x.VracExcluded, Product = p })
.Join(PackedProducts, x => x.VracExcluded.codPackedProduct, pp => pp.codPackedProduct, (x, pp) => new { Order = x.Order, VracExcluded = x.VracExcluded, Product = x.Product, PackedProduct = pp })
.Where(x => x.Order.codOrder == _order.codOrder)
.Select(x => new FinishedProductPrintingM
{
OF = x.Order.codOrder,
Item = "0",
Ligne = x.VracExcluded.codLine,
Material = x.VracExcluded.codPackedProduct,
Produit = x.Product.codProductType,
MaterialDescription = x.PackedProduct.lblPackedProduct,
Lot = x.VracExcluded.codPackedBatch,
RéférenceClient = x.Product.codCustomerColor,
Quantité = x.VracExcluded.nbrPackedQuantity.ToString(),
Déjàimprimé = x.VracExcluded.nbrLabelPrinted
})
.ToList();
Before I asked Prevent sort result of union in entity framework
I got my answer but now I have new problem with this issue. I have this code:
var productExactlyTitle = products.Where(x => x.Title == keyword);
var productStartWithPhrase = products.Where(x => x.Title.StartsWith(keyword));
var productStartWithWord = products.Where(x => x.Title.StartsWith(keyword + " "));
var productContainsWord = products.Where(x => x.Title.Contains(" " + keyword + " "));
var productContainsPhrase = products.Where(x => x.Title.Contains(keyword)
|| x.Title.Contains(keyword)
|| x.SubTitle.Contains(keyword)
|| x.OtherName.Contains(keyword));
var splitWords = keyword.Split(' ');
var productSplitWordSearch = splitWords.Aggregate(products, (current, word) => current.Where(x => x.Title.Contains(word.Trim())));
var p1 = productExactlyTitle.Select(x => new { Item = x, Order = 1 });
var p2 = productStartWithWord.Select(x => new { Item = x, Order = 2 });
var p3 = productStartWithPhrase.Select(x => new { Item = x, Order = 3 });
var p4 = productContainsWord.Select(x => new { Item = x, Order = 4 });
var p5 = productContainsPhrase.Select(x => new { Item = x, Order = 5 });
var p6 = productSplitWordSearch.Select(x => new { Item = x, Order = 6 });
var productList = p1
.Union(p2)
.Union(p3)
.Union(p4)
.Union(p5)
.Union(p6)
.OrderBy(x => x.Order)
.Take(21)
.AsEnumerable()
.Select(x => new ProductItemViewModel()
{
Id = x.Item.Id,
Title = x.Item.Title,
Price = DiscountController.ApplyDiscountToPrice(x.Item).ToPrice(),
Image = x.Item.Images.FirstOrDefault(y => y.IsCoverPhoto)?.ImageUrl
});
Result of above code have duplicate records and I have to use select and distinct to remove duplicate records. so I change my code like this:
var productList = p1
.Union(p2)
.Union(p3)
.Union(p4)
.Union(p5)
.Union(p6)
.OrderBy(x => x.Order)
.Select(x => x.Item)
.Distinct()
.Take(21)
.AsEnumerable()
.Select(x => new ProductItemViewModel()
{
Id = x.Id,
Title = x.Title,
Price = DiscountController.ApplyDiscountToPrice(x).ToPrice(),
Image = x.Images.FirstOrDefault(y => y.IsCoverPhoto)?.ImageUrl
});
But after that my result is sorted with Id column again.
How can I solved this?
First, since adding Order field to each query makes the record unique, using Union (which is supposed to remove duplicates) doesn't make sense, so simply use Concat instead.
Second, to remove duplicates and not lose the Order field needed for later ordering, you need to group by Item and take the minimum Order for each group. The rest is the same as in the original solution.
var productList = p1
.Concat(p2)
.Concat(p3)
.Concat(p4)
.Concat(p5)
.Concat(p6)
.GroupBy(e => e.Item)
.Select(g => new { Item = g.Key, Order = g.Min(e => e.Order) })
.OrderBy(e => e.Order)
.Select(e => e.Item)
.Take(21)
.AsEnumerable()
...
In SQL server union, result is sorted based on primary key column. I want to prevent this behavior in entity framework.
In this post, #praveen has explained how to do this in pure sql. But I want to do this in entity framework.
My code:
public virtual ActionResult Search(string keyword)
{
var products = _db.Products
.Where(x => x.IsActive)
.AsQueryable();
var productExactlyTitle = products.Where(x => x.Title == keyword);
var productStartTitle = products.Where(x => x.Title.StartsWith(keyword));
var productContainsTitle = products.Where(x => x.Title.Contains(keyword)
|| x.Title.Contains(keyword)
|| x.SubTitle.Contains(keyword)
|| x.OtherName.Contains(keyword));
var productList = productExactlyTitle.Union(productStartTitle)
.Union(productContainsTitle)
.Take(10)
.AsEnumerable()
.Select(x => new ProductItemViewModel()
{
Id = x.Id,
Title = x.Title,
Price = x.Price.ToPrice(),
Image = x.Images.FirstOrDefault(y => y.IsCoverPhoto)?.ImageUrl
});
// some code ...
}
I want to show records with below order:
First: records of productExactlyTitle
Second: records of productStartTitle
Third: records of productContainsTitle
But result is sorted with Id column! and I don't want this.
Is there a way for do this?
In SQL all queries without an order by explicitly set is considered unordered. (and EF queries a translated into SQL). So if you want a specific order after your union just specify it.
var result = q1.Union(q2).OrderBy(x => x.?);
For your specific case:
var p1 = productExactlyTitle.Select(x => new { Item = x, Order = 1 });
var p2 = productStartTitle.Select(x => new { Item = x, Order = 2 });
var p3 = productContainsTitle.Select(x => new { Item = x, Order = 3 });
var productList = p1.Union(p2)
.Union(p3)
.OrderBy(x => x.Order)
.Select(x => x.Item)
.Take(10);
I Made a new notMapped class "BuyingHistory", that have some property (not all) of two database tables
how to fill this class with entity? I made the conditions, but how do I select the properties to a list? (I know how to do it for one property but not for a list)
IQueryable<BuyingHistory> _buyingList =
_db.Orders
.Join(_db.EventPages
,o => o.EventID
,e => e.ID
,(o, e) => new { orders = o, events = e })
.Where(o => o.orders.UserID == LS.CurrentUser.ID)
.Select( // I don't know how to continue
it's work in this way bellow, but how can I do it in one command like the example above
var _List =
_db.Orders
.Join(_db.EventPages
, o => o.EventID
, e => e.ID
, (o, e) => new { orders = o, events = e })
.Where(o => o.orders.UserID == LS.CurrentUser.ID).ToList();
List<BuyingHistory> _buyingList = new List<BuyingHistory>();
foreach (var item in _List)
{
_buyingList.Add(new BuyingHistory()
{
CreatedDate = item.orders.CreatedDate,
EventName = item.events.Title,
NumberOfTickets = item.orders.TicketNumber,
OrderID = item.orders.ID,
Status = item.orders.Status.ToString(),
Total = item.orders.TicketNumber
});
}
I'd use query syntax to begin with, and then do the query like so:
from ord in _db.Orders
join evt in _db.EventPages on ord.EventID equals evt.ID
where ord.UserID == LS.CurrentUser.ID
select new BuyingHistory
{
CreatedDate = ord.CreatedDate,
EventName = evt.Title,
NumberOfTickets = ord.TicketNumber,
OrderID = ord.ID,
Status = ord.Status.ToString(),
Total = ord.TicketNumber
})
If you have EF version 6 the ToString() won't throw exceptions. If not, you have to change the type of BuyingHistory.Status into the type coming from the database.
I have a Banner with multiple Packs. Each pack has multiple files.
I have the following query:
List<BannerModel> models = context.Banners
.Select(x => x.Packs
.SelectMany(p => p.Files, (p, f) => new {
Id = p.Id,
Flag = p.Flag,
File = new { Id = f.Id, Flag = f.Flag, Key = f.Key, Mime = f.Mime }
})
.Where(a => a.File.Flag == "Img_200")
.Select(a => new BannerModel { PackId = a.Id, ImageKey = a.File.Key })
).ToList();
1) I get the error on "ToList()".
Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List'
2) Then I removed the ToList and added "var models = ..."
I know there are 10 records where 5 of them satisfy the criteria:
.Where(a => a.File.Flag == "Img_200")
What is strange is that I get 10 items, 5 with data and 5 with no data.
Where I should only get a list of 5 items. The one that satisfy the criteria.
Could someone help me solving this problem?
Thank you,
Miguel
Should this be:
List<BannerModel> models = context.Banners
.SelectMany(x => x.Packs
.SelectMany(p => p.Files, (p, f) => new {
Id = p.Id,
Flag = p.Flag,
File = new { Id = f.Id, Flag = f.Flag, Key = f.Key, Mime = f.Mime }
})
.Where(a => a.File.Flag == "Img_200")
.Select(a => new BannerModel { PackId = a.Id, ImageKey = a.File.Key })
).ToList();