Sunday, October 1, 2017

C# Linq ,Generics, Lamda expression and many more.

Introduction
I'll keep this space updating my most used c# stuff in here. This is work in progress to have list of all referenced code that is useful at times of implementation.

Linq Data Parallelism

var quotes =quotesForAllProducts();//e.g Get quotes for all products
Parallel.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;
          }          
      }

System.Linq.ParallelEnumerable

Set object values for superset.
Packages = poducts.AsParallel().Select(p => new Package
                {
                    tId = p.tId,
                    vId = p.vId
                }).ToList(),

SelectMany

private 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>();

    } 


Left Join DefaultIfEmpty()

public 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();          
       }

No comments :