我使用以下代码:
list.OrderByDescending(x => x.Supporters.Sum(y=>y.Tokens));
(简短说明:任何x都有支持者列表,任何支持者都可以提供一些代币,我需要通过代币的总和来订购x。)
我得到了一个例外:
Unable to cast object of type 'System.Linq.Expressions.MethodCallExpressionN' to type 'System.Linq.Expressions.MemberExpression'."} System.SystemException {System.InvalidCastException}
出了什么问题以及如何使其正确无误? 谢谢你的帮助。
答案 0 :(得分:1)
Tokens
对象上的Supporter
属性是int
还是某些东西的集合?因为如果它是int
它应该可以正常工作,在另一种情况下你应该这样做:
list.OrderByDescending(x => x.Supporters.Sum(y=>y.Tokens.Count()));
答案 1 :(得分:1)
没有看到你的其余代码,这有点棘手。我只是为自己尝试过(见下面的代码),我没有遇到任何问题。
这是我的代码:
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; }
}