2011-04-12 92 views
6

我通过转换现有的项目和我坚持将如下的VB LINQ代码自学C#的过程是:转换VB的LINQ to C#

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)

我mananged到目前为止,转换这么多:

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

'小组由我的难倒。任何帮助将是巨大的......

+0

如果它有帮助任何人,这是代码属于我想要转换和添加到页面的项目:http:// www .codeproject.com/KB/Silverlight的/ ListDragDropSL.aspx – Graeme 2011-04-13 01:37:23

回答

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