skip to Main Content

How can I convert IList objects to string array?

While working on the telegram bot, some difficulties arose. I get a IList<object> from google table with some information. I need to convert this IList<object> to an array of strings. How can I do this?

static void ReadBudgetTypes()
{
    var range = $"{settingsSheet}!B3:B";
    var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);
    var response = request.Execute();
    var values = response.Values; // here i get list of objects from google table

    if (values != null && values.Count > 0)
    {
        foreach (var row in values)
        {
            Console.WriteLine("{0}", row[0]);
        }
    }
    else
    {
        Console.WriteLine("No data!");
    }
}

3

Answers


  1. you can try this:

    var tempList=List<string>();
    string[] arrayList=null;
    if (values != null && values.Count > 0)
     {
          foreach (var row in values)
          {
             tempList.Add(row[0]);
          }
       arrayList=tempList.ToArray();
    }
    
    Login or Signup to reply.
  2. Try something like this:

        IList<object> list = new List<object>(){ "something", "something else" };
        string[] array = list.Select(item => (String)item).ToArray();
    
    Login or Signup to reply.
  3. Assuming cells may not be strings and may (or may not) have null values, you can print for each cell of the row:

    // assumes ToString() gives a meaningful string
    var listOfStrings = row.Select(x => x?.ToString()).ToList();
    foreach(string cell in listOfStrings)
        Console.WriteLine(cell);
    

    or the whole row, joined by a separator

        Console.WriteLine(string.Join(", ", row);
    

    If you know the cells are strings you can just cast

    var listOfStrings = row.Cast<string>().ToList();
    // or
    var listOfStrings = row.Select(x => (string)x).ToList();
    

    and then repeat either of the above (loop or string.Join).

    If items could be null,

    var listOfStrings = row.Select(x => (x ?? (object)"").ToString()).ToList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search