如何解决以下错误:无法从'转换为'& # 39; System.Collections.Generic.
本文关键字:转换 Generic Collections System 解决 何解决 错误 | 更新日期: 2023-09-27 18:09:04
我正在尝试jtree,我使用mvc项目来填充树。
到目前为止工作得很好,但现在我决定将一个属性从string更改为int。
我这样做是因为我正在改变的属性是一个ID属性,我想从我拥有的列表中获得最高的ID,并将其增加1。
代码:List<TreeNode> Nodes = getTreenodeList();
var NewId = Nodes.Select(x => x.Id.Max()) +1;
上面的代码给了我以下错误:"不能从'int'转换为'System.Collections.Generic.IEnumerable"
getTreenodeList:
public static List<TreeNode> getTreenodeList()
{
var treeNodes = new List<TreeNode>
{
new TreeNode
{
Id = 1,
Text = "Root"
},
new TreeNode
{
Id = 2,
Parent = "Root",
Text = "Child1"
}
,
new TreeNode
{
Id = 3,
Parent = "Root",
Text = "Child2"
}
,
new TreeNode
{
Id = 4,
Parent = "Root",
Text = "Child3"
}
};
// call db and get all nodes.
return treeNodes;
}
最后是treeNode类:
public class TreeNode
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "parent")]
public string Parent { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
[JsonProperty(PropertyName = "icon")]
public string Icon { get; set; }
[JsonProperty(PropertyName = "state")]
public TreeNodeState State { get; set; }
[JsonProperty(PropertyName = "li_attr")]
public string LiAttr { get; set; }
[JsonProperty(PropertyName = "a_attr")]
public string AAttr { get; set; }
}
到目前为止,我的谷歌搜索结果给了我一些尝试,通过使用firstdeafut,我发现应该转换ienumrable到int,但遗憾的是,没有工作。我还尝试过其他几种情况,但都没有效果。
我可以诚实地说,我真的不明白这里的问题是什么,所以如果有人有答案,我也会非常感谢一个解释。
谢谢!
这个语句(如果工作)
Nodes.Select(x => x.Id.Max())
将返回一个IEnumerable<int>
而不是单个Int
。将其替换为:
Nodes.Select(x => x.Id).Max()
此外,您的字段Id
将持有单个Value
,因此在其上应用Max
是错误的。
你的代码应该是:
var NewId = Nodes.Select(x => x.Id).Max() + 1;
你必须这样做才能获得最大id:
var NewId = Nodes.Max(x => x.Id) +1;
更多细节和理解请参考:
http://code.msdn.microsoft.com/LINQ-Aggregate-Operators-c51b3869 MaxElements
http://msdn.microsoft.com/en-us/library/bb397947.aspx http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b