将VB Linq转换为c#



我正在通过转换现有项目来自学c#,并且在转换以下vb linq代码时卡住了:

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

其中Products As ObservableCollection(Of ProductModel)

到目前为止,我已经成功地转换了这么多:

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};

"Group By"把我难住了。

你的问题有点复杂,很难理解,但让我试着描述一下我认为你在寻找什么。您有一个product列表,每个product可能有一个或多个标签;你想要一个所有标签的列表,包括有多少产品有这个标签,有这个标签的产品被浏览的总次数,有这个标签的产品被点赞的总次数。如果是这种情况,下面的代码应该可以解决这个问题:

// 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)
                          };

你的代码看起来有点疯狂:)…很难理解你真正想要的是什么,但我认为这就是它:

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 => x.v),
        LikesTotal = g.Sum(x => x.nl),
    });

相关内容

  • 没有找到相关文章

最新更新