gpt4 book ai didi

c# - 将 VB Linq 转换为 C#

转载 作者:太空狗 更新时间:2023-10-29 21:59:24 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于c# - 将 VB Linq 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5632302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com