I'm in the process of teaching myself C# by converting an existing project and am stuck converting the following vb linq code:
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开发者_JAVA百科_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
where Products As ObservableCollection(Of ProductModel)
I've mananged to convert this much so far:
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};
The 'Group By's has me stumped. Any help would be great...
Your query is a little convoluted and hard to follow, but let me try to describe what I think you are looking for. You have a list of Products, each of which may have one or more tags; and you want a list of all of the tags, with the count of how many products have that tag, the total number of views of products with that tag, and the total number of "likes" of the product with that tag. If that is the case, the following should do the trick:
// 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)
};
Your code looks a little crazy :) ... it's hard to understand what you actually want, but I think this is it:
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),
});
精彩评论