Search code examples
c#neo4jclient

How to assign data to a variable?


I'm trying to assign data from Neo4j database to a variable in C# according to available examples like so:

    var born = graphClient.Cypher
            .Match("(person:Person)")
            .Where((Person person) => person.name == "Tom Hanks")
            .Return(person => person.As<Person>().born)
            .Results;

But when i try to print the value out :

    Console.WriteLine(born);

I get this in console :

    System.Collections.Generic.List`1[System.Int32]

What I'm doing wrong?


Solution

  • From your output, you are receiving in results a collection of items which match your filter. If you want to print the first element, you can do something like:

    Console.WriteLine(born.First());
    

    Just keep in mind that in that collection it could be more than one element...

    If you want to print all the born items, you can use a foreach loop to do so: You only have to do something like:

    foreach (var item in born)
    {
        Console.WriteLine(item);
    }
    

    the use of the foreach loop is the best approach because even when you have 0 elements in the collection, it works as expected (i.e: it doesn't fail or throw an exception) You have to be careful with the use of the First() there because it will throw an exception if your collection is empty. So if you know that you can end up with an empty collection you can always use FirstOrDefault() which return null - or the default value according to the data type - in case of an empty collection