【问题标题】:Converting VB Linq to C#将 VB Linq 转换为 C#
【发布时间】:2011-04-12 08:20:17
【问题描述】:

我正在通过转换现有项目来自学 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”让我难过。任何帮助都会很棒...

【问题讨论】:

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


【解决方案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)
                          };

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多