Question

i have a table that has zero to many children. just like how this site has a QUESTION which can have zero to many VOTES (either Up == 1 or Down == 0).

I need to get all questions that have the most up votes. Eg. all the questions, ordered by Sum(Vote) descending.

I'm not sure how to do it in linq.

So i would have an EntitySet called Questions and another EntitySet called Votes.

I was trying to do group by and let and order by and nothing compiles :(

Could anyone have any suggestions, please?

Was it helpful?

Solution

myDataContext.Questions
  .OrderByDescending(q => q.Votes.Select(v => v.VoteValue).Sum())

In query comprehension (unchecked):

from q in myDataContext.Questions
order q by 
(
  from v in q.Votes
  select v.VoteValue
).Sum() descending
select q;

OTHER TIPS

That mostly depends on your data but here's a small sample:

XElement xdoc=XElement.Parse(@"
  <root>
    <question name=""A"">
      <vote type=""up"" />
      <vote type=""down"" />
    </question>
    <question name=""B"">
      <vote type=""up"" />
      <vote type=""up"" />
    </question>
    <question name=""C"" />
  </root>
  ");

var result=
  from q in xdoc.Elements("question")
  let votes=q.Elements("vote").Count(v=>v.Attribute("type").Value=="up")
  orderby votes descending
  select new
  {
    Name=q.Attribute("name").Value,
    Votes=votes
  };

foreach (var r in result)
{
  Console.WriteLine(r.Name+" "+r.Votes);
}

Since you are using EntitySet I gather it is Linq2SQL? Assuming you have references set up properly and have a Vote.Question property:

(from v in dc.Votes
where v.IsUpVote // v.Vote == 1 (??)
group v by v.Question into q
select new { Question = q.Key, UpVotes = q.Count() }).OrderByDescending(e => e.UpVotes);

I gather here Count() is actually what you want? Sum() would produce the same, but is perhaps not as meaningfull(?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top