Reputation: 1092
I use piece of code as following:
list.OrderByDescending(x => x.Supporters.Sum(y=>y.Tokens));
(short explanation: any x has list of Supporters,any Supporter can give some tokens, I need to order x by sum of token).
and I got an exeption:
Unable to cast object of type 'System.Linq.Expressions.MethodCallExpressionN' to type 'System.Linq.Expressions.MemberExpression'."} System.SystemException {System.InvalidCastException}
What's wrong and how to make it correct? Thanks for help.
Upvotes: 0
Views: 155
Reputation: 67
Without seeing the rest of your code it's a bit tricky. I just tried it for myself (see code below) and I didn't get any problems.
Here's my code:
static void Main(string[] args)
{
List<Team> list = new List<Team>
{
new Team { Name = "1", Supporters = new List<Supporter>
{
new Supporter { Name = "Bob", Tokens = 4 },
new Supporter { Name = "Sarah", Tokens = 3 },
new Supporter { Name = "Jane", Tokens = 6 },
} },
new Team { Name = "2", Supporters = new List<Supporter>
{
new Supporter { Name = "Brian", Tokens = 4 },
new Supporter { Name = "Ellie", Tokens = 19 },
new Supporter { Name = "Steve", Tokens = 12 },
} },
new Team { Name = "3", Supporters = new List<Supporter>
{
new Supporter { Name = "John", Tokens = 7 },
new Supporter { Name = "Vern", Tokens = 11 },
new Supporter { Name = "Peter", Tokens = 18 },
} },
};
var results = list.OrderByDescending(x => x.Supporters.Sum(y => y.Tokens));
}
}
class Team
{
public string Name { get; set; }
public List<Supporter> Supporters { get; set; }
}
class Supporter
{
public string Name { get; set; }
public int Tokens { get; set; }
}
Upvotes: 1
Reputation: 7448
The Tokens
property on the Supporter
object is an int
or a collection of something? Because if it's an int
it should work fine, in the other case you should do:
list.OrderByDescending(x => x.Supporters.Sum(y=>y.Tokens.Count()));
Upvotes: 1