Reputation:
var result =surveyEntities.Candidates.Join(surveyEntities.Votes,
t=>t.CandidateID,
d=>d.CandidateID,
(t,d)=> new {
t=t,
d=d
}).GroupBy( temp0=> new {
Name= temp0.t.Name, CandidateID=temp0.t.CandidateID,
Image=temp0.t.Image
},
temp0=>temp0.d).Select(g=> new number1{
CandidateID = g.Key.CandidateID,
Name = g.Key.Name,
Image= g.Key.Image,
**count= g.Count(p=>p.CandidateID)**}).ToList();
}
I am getting error on following code 'count= g.Count(p=>p.CandidateID)'. I have create a separate class number1 for handling anonymous class but issue is not resolved please help me to find where is the issue.
thanks in advance
Upvotes: 1
Views: 1771
Reputation:
It looks like you're trying to group votes by candidate. First you're joining candidates to votes, then grouping votes by new objects that sum up a candidate's identity, then trying to get the total votes by those candidate. Correct?
If so, Christos' answer is correct, but if I may rephrase it: .Count(...)
is meant really as a count-when-true, meaning, count things when the condition in the lambda is true. But you're not using the lambda to return a bool for a when-true, like p.CandidateID != null
would be.
His just-use-.Count() by itself should work. However, beyond that, if my interpretation is right, your whole Linq statement can be simplified to something like the following:
var result = surveyEntities.Candidates
.GroupJoin(
surveyEntities.Votes,
c => c.CandidateID,
v => v.CandidateID,
(c, v) => new {
Name = c.Name,
ID = c.CandidateID,
Pic = c.Image,
Votes = v.Count() }
);
Which should also evaluate faster if there are large numbers of votes (or, maybe, candidates).
Upvotes: 1
Reputation: 53958
The signature of the method, Count
, you use is the following:
public static int Count<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
The p.CandidateID
is an integer, so for each item (TSource
) you return an int
, which is not correct. For each item of the collection you should return a boolean, or an expression that can be evaluated as a boolean.
E.g. something like this is a proper syntax:
g.Count(p=> p.CandidateID > 0)
Apparently this may doesn't make any sence in your case, but has the proper syntax.
The thing that you might want is the number of items each group has. If this is true, you can just use the following:
g.Count()
Upvotes: 3