I have two LINQ expressions that I think I should be able to combine into one.
I have a list of referrers, each of which references multiple items, and I'm trying to determine the most popular items. Each referrer conveys a unique vote score to a referenced item. That is, referrer 1 might give a vote of 0.2, and referrer 2 might give a vote of 0.03.
A simplified Referrer
class:
class Referrer
{
public double VoteScore { get; private set; }
public List<int> Items { get; private set; }
public Referrer(double v)
{
VoteScore = v;
Items = new List<int>();
}
}
My two Linq expressions are:
var Votes =
from r in Referrers
from v in r.Items
select new { ItemNo = v, Vote = r.VoteScore };
That gives me a list:
ItemNo:1, Vote:0.2
ItemNo:3, Vote:0.2
ItemNo:1, Vote:0.03
Now, I can group, sum, and sort with my second expression:
var SortedByScore =
from v in Votes
group v by v.ItemNo into g
let score = g.Sum((v) => v.Vote)
orderby score descending
select new { ItemNo = g.Key, Score = score };
Is it possible to combine these into a single expression? I realize that I can chain the expressions, that is:
var SortedByScore =
from v in
(from r in ActivatedReferrers
from v in r.Items
select new { ItemNo = v, Vote = r.VoteScore })
group v by v.ItemNo into g
let score = g.Sum((v) => v.Vote)
orderby score descending
select new { ItemNo = g.Key, Score = score };
But that's not really any different from what I already have--it's just nesting the first expression inside the second. Is there another way that combines the two expressions into one?
How about:
from r in Referrers
from v in r.Items
group r.VoteScore by v into g
let score = g.Sum()
orderby score descending
select new { ItemNo = g.Key, Score = score }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With