Friday, September 27, 2019

Linq


1. Checks if any of the items in the list are also contained in another list

- Flattens our .Filters object to get ID's
- Checks if any of the filter ID's are in the list of tagGuids (array of guids)

string[] tagGuids = new string[] { };

            if (!string.IsNullOrEmpty(tags))
            {
                tagsPredicate = PredicateBuilder.False<ProductSearchItem>();
                tagGuids = tags.Split(',');

                foreach (string tagGuidString in tagGuids)
                {
                    Guid tagGuid = Guid.Parse(tagGuidString);
                    tagsPredicate = tagsPredicate.Or(p => p.ContentTags.Contains(tagGuid));
                }
            }



                _HapiResults = new ProductSearchController().GetProductCategorySearchResults(searchTerm, cartContext)
                    .Where(x => tagGuids.Any(t => x.Filters.Select(f => f.Id).Contains(t))).ToList(); 



2. Select new

unifiedProducts.AddRange(_AllNonProductResults.Select(e => new UnifiedProduct
                    {
                        Name = (!string.IsNullOrEmpty(e.ProductTitle)) ? e.ProductTitle : e.Title,
                        PifType = (!string.IsNullOrEmpty(e.Pif_Type)) ? e.Pif_Type : string.Empty,
                        IsGeneric = (IsNotProductOrGene(e)) ? true : false,
                        Description = StringUtil.Clip(e.Teaser_Text, 350, true),
                        Url = e.Url,
                        ExactMatchResult = null,
                        GeneNodeId = (!string.IsNullOrEmpty(e.ProductTitle)) ? e.ProductTitle : e.Title,
                        Symbol = null
                    }).ToList());


3. SelectMany (flattens out second layer list)

 List<Filter> hapiFilters = hapiModel.Results
                 .SelectMany(r => r.Filters)
                 .GroupBy(f => f.Item1)
                 .Select(fg => new Filter()
                 {
                     FilterName = fg.Key,
                     FilterItems = fg.GroupBy(fi => fi.Item2).Select(fi => new FilterItem()
                     {
                         FilterItemName = fi.Key,
                         FIlterItemGuid = fi.Key,
                         Count = fg.Count()
                     }).ToList()
                 }).ToList();

No comments:

Post a Comment