I would rather named the title as Linq performance pit stop. Anyway in the interest of time, here is, one of the good examples of how we can start with something very trivial linq query to something convoluted one. Always remember the query in memory or on fly comes with its own pros and cons. One must understand how to use them and when. I took this particular example from pluralsight and thought it to be worth sharing.
Courtesy
https://app.pluralsight.com/library/courses/linq-more-effective/table-of-contents
by Mark Heath.
Slow
var longest=books.First(b => b.Pages==books.Max(a => a.Pages));
Better
var mostBooks= books.Max(a => a.Pages);
var longest=books.First(b => b.Pages == mostBooks);
Best
var longest= books.MaxBy(p => p.Pages);
Hope this useful.
Courtesy
https://app.pluralsight.com/library/courses/linq-more-effective/table-of-contents
by Mark Heath.
Slow
var longest=books.First(b => b.Pages==books.Max(a => a.Pages));
Better
var mostBooks= books.Max(a => a.Pages);
var longest=books.First(b => b.Pages == mostBooks);
Best
var longest= books.MaxBy(p => p.Pages);
Hope this useful.
SingleOrDefault()
Check before using FirstOrDefault
This should be used if query returns single recordset.
var scalarDataSet= result?.Results?.SingleOrDefault();
Linq Data Parallelismvar quotes = quotesForAllProducts();//e.g Get quotes for all productsParallel.ForEach(products, item => Process(item,quotes));private void Process(Product item,List<Quote> quotes) { var quote= quotes?.SingleOrDefault (p => p.Id.Trim().Equals(item.Id ?? string.Empty)); if (quote != null) { item.Cost = quote.TotalAmount.GetValueOrDefault(); item.Code = quote.Code; } }ParrallelismSystem.Linq.ParallelEnumerableSet object values for superset.Packages = poducts.AsParallel().Select(p => new Package { tId = p.tId, vId = p.vId }).ToList(),SelectManyprivate void SetProductsSubSet(IList<Product> products) { _products= (IEnumerable<ProductDetail>) products?.AsParallel().SelectMany(a => a.subLevel.Select(p => new ProductDetail { Id = a.Id, Type = a.Type, })) ?? new List<ProductDetail>(); }DefaultIfEmpty() Left Joinpublic List<Product> AddHospitalAndExtrasProduct() { return (from A in Main join B in SubB on A.ID equals B?.Id into MainAndSubB from ResultSetA in MainAndSubB.DefaultIfEmpty() join B in SubC on A.ID equals C?.Id into MainAndSubC from ResultSetC in MainAndSubC.DefaultIfEmpty()select new Product { Id = Main.Id, Name = Main.Name, SubBId = ResultSetA != null ? ResultSetA .SubBId : string.Empty, SubCId = ResultSetC != null ? ResultSetC .SubCId : string.Empty, }).ToList(); }