Question

I wanna convert an object Array called "list" into a string Array called "test". Attached the code. The Problem is, the function is returning "System.Collections.Generic.Dic..." and not the strings in SQL database. Thanks..

Code:

    public string[] ListMethod(string command)
    {
        MySqlCommand comm = new MySqlCommand(command, conn);
        MySqlDataReader commreader;
        commreader = comm.ExecuteReader();

        var list = new List<IDictionary<string, object>>();           

        while (commreader.Read())
        {
            var record = new Dictionary<string, object>();

            for (int i = 0; i < commreader.FieldCount; i++)
            {
                var key = commreader.GetName(i);
                var value = commreader[i];
                record.Add(key, value);
            }

            list.Add(record);
        }
        string[] test = ((IEnumerable)list).Cast<object>().Select(x => x.ToString()).ToArray();
        return test;
    }
Was it helpful?

Solution

Lets look at your LINQ Query:

string[] test = ((IEnumerable)list).Cast<object>().Select(x => x.ToString()).ToArray();

What you are saying to the compiler here is:

Cast all objects in the list of dictionaries to object, and then execute to ToString() method of each object (which by default always prints the name of the class) and set it to an array (The cast do IEnumerable is redundant since List implements that interface anyway.

What you actually need to do is:

var test = list.Select(x => x.Values.ToString()).ToArray();

assuming all your values in the IDictionary are actually strings, this will fetch them for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top