Iterate "Task<IEnumerable<T>>" in c#?

Viewed 259

I am playing with Scylla db and working with C# for the first time in 15 years.

After reading about Scylla and C# for few days I got below code. In the below code, I connect to the scylla cluster and try to query a table to get data from it.

public static async void test()
{
    var cluster = Cluster.Builder().AddContactPoints("test-endpoint").WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum)).Build();
    var session = cluster.Connect("processks");
    var mapper = new Mapper(session);

    var cql = Cql.New("SELECT * FROM test LIMIT 10");
    var fetchResult = await mapper.FetchAsync<User>(cql).ConfigureAwait(false);
    // this just prints the object which is not what I want
    Console.WriteLine(fetchResult);
}

Below is my User class:

using System.Collections.Generic;
using Cassandra.Mapping;
using Cassandra.Mapping.Attributes;

namespace Test.Objects.POCO.Scylla
{
    [TableName("test")]
    [PrimaryKey("client_id")]
    public class User
    {
        [Column("client_id")]
        public int ClientId { get; set; }

        [Column("md")]
        public string MD { get; set; }

        [Column("process_ids")]
        public List<int> ProcessIds { get; set; }
    }
}

How can I iterate fetchResult object to print out the data I got back after executing the above query?

This is the code link of Mapper class where FetchAsync method is defined and it returns Task<IEnumerable<T>> object back.

1 Answers
var fetchResult = await mapper.FetchAsync<User>(cql).ConfigureAwait(false);

fetchResult will be a IEnumerable<User> so it's up to you to iterate over the IEnumerable however you want to and print the underlying User objects with whatever method you prefer.

Console.WriteLine prints the result of the provided object's ToString() method and neither the returned IEnumerable object nor the contained User objects have the default implementation that you're looking for.

You can implement ToString() on the User class and do something like this:

Console.WriteLine(string.Join(Environment.NewLine, fetchResult));

Or you can just use a JSON library to convert the user object to a JSON string instead of overriding ToString():

Console.WriteLine(string.Join(
    Environment.NewLine, 
    fetchResult.Select(user => JsonConvert.SerializeObject(user))))

[EDIT] you might be interested in our examples and docs:

https://www.datastax.com/examples (you can filter by C# language)

https://docs.datastax.com/en/developer/csharp-driver/3.14/features/components/mapper/

Related