Home > Enterprise >  how get item from list which is in Array of Object in c#
how get item from list which is in Array of Object in c#

Time:01-19

This is my code, i can`t to get element from list which is situated Object array. How i can get "info" from data.

Object[] data = {
new List<string>() {"name", "name2", "name3", "name4",},
new List<string>() { "info", "info2", "info3", "info4",},
new List<int>() { 2002, 1999, 2005, 1980 },
new List<int>() { 12000, 1000000, 2500, 900000 },
new List<int>() { 1337, 2828, 1890, 4210 },
};

i tried to get element with the help:

var i = data[1][1]
var i = data[1,1]

CodePudding user response:

You're treating an Object array as if it were a List array. In order to use an indexing operator on an element retrieved from the array, you'll need to denote that it's a List.
This is most commonly done with the as, is, typeof, and/or casting operators.
Here's an example using as and is:

object[] data = {
new List<string>() {"name", "name2", "name3", "name4",},
new List<string>() { "info", "info2", "info3", "info4",},
new List<int>() { 2002, 1999, 2005, 1980 },
new List<int>() { 12000, 1000000, 2500, 900000 },
new List<int>() { 1337, 2828, 1890, 4210 },
};

foreach (var item in data)
{
    if (item is List<string>)
        Console.WriteLine((item as List<string>)[0]); // Use the string however you want
}

For more information, I'd take a look at Microsoft's Type-testing documentation.

CodePudding user response:

data[1] is not a list, it's an object, technically it is object?. so you cant use the index on it.

you can get the value like this.

var ls = data[1] as List<string>;

var item = ls[1];

or var item = ((List<string>)data[1])[1];

  • Related