簡體   English   中英

將VB Linq轉換為C#

[英]Converting VB Linq to 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'讓我難過。 任何幫助都會很棒......

您的查詢有點令人費解,難以理解,但讓我試着描述一下我認為您正在尋找的內容。 您有一個產品列表,每個產品可能有一個或多個標簽; 並且您需要所有標簽的列表,包含該標簽的產品數量,帶有該標簽的產品的總瀏覽量以及帶有該標簽的產品的“喜歡”總數。 如果是這種情況,以下應該可以解決問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM