Reputation: 3456
I am experimentin with jstree and im using an mvc project to populate the tree.
It has worked good so far but now i decied to chnage a property from string to int.
I do this because the property im changingis an ID property and i want to get the highest id from a list that i have and increment it with one.
code:
List<TreeNode> Nodes = getTreenodeList();
var NewId = Nodes.Select(x => x.Id.Max()) +1;
The code above gives me the following error: "cannot convert from 'int' to '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;
}
And finaly the treeNode class:
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; }
}
So far my googeling result gave me a few attempts at this by using firstorDeafut which i found should convert the ienumrable to int but sadly that did not work. I have tried a few other scenarios but none of them have helped.
I can honestly say that I don't really understand what the problem is here so if anyone out there has an answer i would deeply appreciate an explenation aswell.
Thanks!
Upvotes: 3
Views: 5429
Reputation: 223422
This statement (if worked)
Nodes.Select(x => x.Id.Max())
would return an IEnumerable<int>
and not a single Int
. Replace it with:
Nodes.Select(x => x.Id).Max()
Also Your field Id
would be holding a single Value
, so to apply Max
on it would be wrong.
Your code should be:
var NewId = Nodes.Select(x => x.Id).Max() + 1;
Upvotes: 2
Reputation: 62498
you have to do like this to get the max id:
var NewId = Nodes.Max(x => x.Id) +1;
For more details and understanding refer:
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
Upvotes: 2