将VB Linq转换为C#

时间:2011-04-12 08:20:18

标签: c# vb.net linq c#-4.0 linq-to-objects

我正在通过转换现有项目来自学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};

'By By'让我难过。任何帮助都会很棒......

2 个答案:

答案 0 :(得分:1)

您的查询有点令人费解,难以理解,但让我试着描述一下我认为您正在寻找的内容。您有一个产品列表,每个产品可能有一个或多个标签;并且您需要所有标签的列表,包含该标签的产品数量,带有该标签的产品的总浏览量以及带有该标签的产品的“喜欢”总数。如果是这种情况,以下应该可以解决问题:

// 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 :(得分:0)

你的代码看起来有点疯狂:) ...很难理解你真正想要的东西,但我认为就是这样:

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