Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to combine these two Linq expressions?

Tags:

c#

linq

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?

like image 848
Jim Mischel Avatar asked Jan 26 '11 19:01

Jim Mischel


1 Answers

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 }
like image 181
Allon Guralnek Avatar answered Nov 04 '22 15:11

Allon Guralnek