Convert VB Linq to C #

I am currently participating in C # converting an existing project and forcing the following vb linq code to be converted:

Dim outStuff = From tt In (From t In Products.SelectMany(Function(p) If(p.tags IsNot Nothing, p.tags, New ObservableCollection(Of TagModel))) Group By tagName = t.name, v = (Aggregate p In Products Where If(p.tags IsNot Nothing, p.tags.Contains(t), Nothing) Into Sum(p.views)), nl = (Aggregate p In Products Where If(p.tags IsNot Nothing, p.tags.Contains(t), Nothing) Into Sum(p.num_likes)) Into g = Group, Count()) Group By name = tt.tagName Into Count = Sum(tt.Count), viewsTotal = Sum(tt.v), num_likesTotal = Sum(tt.nl) Select name, Count, viewsTotal, num_likesTotal 

where Products As ObservableCollection(Of ProductModel)

I changed it so far:

 var x = Products.SelectMany(p => (p.tags != null) ? p.tags : new ObservableCollection<TagModel>()); var tags = from t in x group t by t.name into g select new { tagname=g.First().name}; 

"The group" I am entwined. Any help would be excellent ...

+6
source share
2 answers

Your request is a bit confusing and difficult to follow, but let me try to describe what you think you are looking for. You have a list of products, each of which can have one or more tags; and you want the list of all tags to be counted, how many products this tag has, the total number of product views with this tag, and the total number of β€œlikes” of the product with this tag. If so, the following should do the trick:

 // may want to add ToArray() here so that filter is not executed multiple times during subsequent query var productsWithTags = Products.Where(p => p.tags != null); var outStuff = from t in (from p in productsWithTags from t in p.tags select t).Distinct() let matchingProducts = productsWithTags.Where(p => p.tags.Contains(t)) select new { name = t.name, Count = matchingProducts.Count(), viewsTotal = matchingProducts.Sum(p => p.views), num_likesTotal = matchingProducts.Sum(p => p.num_likes) }; 
+1
source

Your code looks a little crazy :)) it's hard to understand what you really want, but I think this is it:

 var outStuff = Products.SelectMany(p => p.tags) .Where(t => t != null) .GroupBy(t => t.name) .Select(g => new { Name = g.Key, Count = g.Sum(), ViewsTotal = g.Sum(x => xv), LikesTotal = g.Sum(x => x.nl), }); 
0
source

Source: https://habr.com/ru/post/885707/


All Articles