2011-04-12 93 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) 
          };