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

I have two LINQ expressions that I think I can combine into one.

I have a list of referrers, each of which refers to several elements, and I'm trying to identify the most popular elements. Each referrer transfers a unique score to the reference point. That is, source 1 can give a vote of 0.2, and referee 2 can give a vote of 0.03.

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:

 var Votes = from r in Referrers from v in r.Items select new { ItemNo = v, Vote = r.VoteScore }; 

This 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 them into one expression? I understand that I can associate expressions, namely:

 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 this is actually no different from what I already have, it's just an embedding of the first expression in the second. Is there any other way that combines two expressions into one?

+6
c # linq
source share
1 answer

What 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 } 
+4
source share

All Articles