Search code examples
.netneo4jcypherneo4jclient

How get a collection of objects <edge, vertex> Neo4jClient .NET Cypher vs. C#


    public IEnumerable<EdVeObj> Parse(string word)
    {
        var res = graphClient.Cypher.OptionalMatch($"(a{{name:'{word}'}})-[r]->(b)") 
        .Return((a, r, b) => new EdVeObj{RelUp = r.As<Edge>(), Target = b.<Vertex>()}).Results;            
        return res;
    }
    public class EdVeObj
    {                
        public Edge RelUp { get; set; }
        public Vertex Target { get; set; }
    }

I need to go through all the outgoing edges and get a collection of objects: the edge plus the vertex to which it comes. Tell me please: how to perform this iteration?


Solution

  • The question isn't super clear, but as Gabor has mentioned, if you're looking to iterate through your results, you use foreach, i.e.:

    var results = Parse("word");
    foreach(var ev in results){
        //Do something with ev
    }
    

    You could equally use a for loop - but you'd need to .ToList() the results:

    var results = Parse("word").ToList();
    for(int i = 0; i < results.Count; i++){
        //Do something with results[i]
    }
    

    Your cypher would benefit from a bit of tuning, first off - there's no need to use OptionalMatch - you need the results to exist, if there's nothing there then it would return nothing anyway. Also - you really should be using a label of some variety, at the very least on the a node. You should also use parameters to get some more performance from the server.

    I would change your code to:

    public IEnumerable<EdVeObj> Parse(string word)
    {
        var res = graphClient.Cypher
            .Match("(:YOUR_LABEL_HERE {name:$word})-[r]->(b)") 
            .WithParam("word", word)
            .Return((r, b) => new EdVeObj
                {
                    RelUp = r.As<Edge>(), 
                    Target = b.<Vertex>()
                })
            .Results;            
    
        return res;
    }
    

    On any big graph this is going to be pretty long running :/