无法将类型从 System.Collection.Generic.IEnumerable.MyClass<Node> 隐式转换为 MyClass<Node>

Cannot implicitly convert type from System.Collection.Generic.IEnumerable.MyClass<Node> to MyClass<Node>

以下是生成错误的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Neo4jClient;
using Neo4jClient.Cypher;

namespace ConsoleApplication1
{   
    public class SNode
    {
        public int shelfid { get; set; }
        public int floorid { get; set; }
    }

    public class PathsResult<TNode>
    {
        public IEnumerable<Node<TNode>> Nodes { get; set; }
        public IEnumerable<RelationshipInstance<object>> Relationships { get; set; }
    }

    class Program
    {
        public static PathsResult<SNode> getPath(int sourceShelfId, int destinationShelfId, GraphClient client)
        {
            var pathsQuery =
            client.Cypher
                .Match("p = shortestPath((src:Node)-[*..150]-(dest:Point))")
                .Where((SNode src) => src.shelfid == sourceShelfId)
                .AndWhere((SNode dest) => dest.shelfid == destinationShelfId)
                .Return(p => new PathsResult<SNode>
                {
                    Nodes = Return.As<IEnumerable<Node<SNode>>>("nodes(p)"),
                    Relationships = Return.As<IEnumerable<RelationshipInstance<object>>>("rels(p)")
                });

            var res = pathsQuery.Results;
            return res;
        }
    }
}

我收到的错误是:

Cannot implicitly convert type System.Collection.Generic.IEnumerable<ConsoleApplication1.PathResult<ConsoleApplication1.SNode> > 
to ConsoleApplication1.PathResult<ConsoleApplication1.SNode> >. An explicit conversion exists, are you missing a cast?

根据我的理解 pathQuery.result 应该 return 一个 PathResult 对象。但是,我尝试根据上面的错误进行转换,如下所示:

var res = pathsQuery.Results.AsEnumerable<PathsResult<SNode> >;

现在它给出的新错误是:

Cannot assign method group to implicitly-typed local variable

我哪里错了?

你有几种可能性:

  1. getPath 的 return 类型更改为 IEnumerable...
  2. 仅使用查询结果的第一个元素:添加.FirstOrDefault()

    var res = pathsQuery.Results.FirstOrDefault();
    

通常设置断点并将鼠标悬停在var上检查它是什么类型是个好主意。在这种情况下最好避免 var 并让编译器报告所有问题。