【问题标题】:how to solve the following error: cannot convert from 'int' to 'System.Collections.Generic.IEnumerable<int>?如何解决以下错误:无法从 'int' 转换为 'System.Collections.Generic.IEnumerable<int>?
【发布时间】:2014-06-17 15:42:59
【问题描述】:

我正在尝试使用 jstree,并且我正在使用 mvc 项目来填充树。

到目前为止它运行良好,但现在我决定将属性从字符串更改为 int。

我这样做是因为我正在更改的属性是一个 ID 属性,我想从我拥有的列表中获取最高 id 并将其递增一。

代码:

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; }
    }

到目前为止,我的谷歌搜索结果通过使用 firstorDeafut 给了我一些尝试,我发现应该将 ienumrable 转换为 int,但遗憾的是这不起作用。我尝试了其他一些场景,但没有一个有帮助。

老实说,我真的不明白这里的问题是什么,所以如果有人有答案,我也会非常感谢你的解释。

谢谢!

【问题讨论】:

    标签: c# linq asp.net-mvc-4 linq-to-objects


    【解决方案1】:

    此声明(如果有效)

    Nodes.Select(x => x.Id.Max())
    

    将返回一个IEnumerable&lt;int&gt; 而不是一个Int。替换为:

    Nodes.Select(x => x.Id).Max()
    

    此外,您的字段Id 将持有一个Value,因此在其上应用Max 将是错误的。

    你的代码应该是:

    var NewId = Nodes.Select(x => x.Id).Max() + 1;
    

    【讨论】:

    • 非常感谢!我还在学习 linq,所以尝试和错误已经开始。很遗憾,我花了 2 小时研究 b4 我终于发布了。
    • @Ra3IDeN,不客气 :)。别担心,这种事情我们大多数人都发生过。
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多