Home > other >  How to store multiple datatype values into single list without defining class?
How to store multiple datatype values into single list without defining class?

Time:12-31

Expected result :

List<something> obj = new List<something>(); //something is i need.
string[] val = new string[] {"hi","20"}; //here I used static but input data fetch from CSV file. So we don't know when which type of data will come?.
int intval;
for(int i=0;i<val.Length;i  )
{
      if(int.TryParse(val[i],out intval)
      {
          obj.add(intval);   //here I face the error "Cannot implicitly convert int to string"
      }
      else
      {
          obj.add(val[i]);
      }
}

I need to add int value and also string value into the same list. But The condition is Developer don't know when which type of value will come. So here I used TryParse to convert values and store into list.


How to declare a list or any other methods are there?

Note: Don't use Class to declare field and define like List<classname> val = new List<classname>();

CodePudding user response:

Not sure why you want to do this but I think the code below is what you're looking for. I suppose you can later check if each list value typeof is string/int but why store multi value types in one list like this?

string[] val = new string[] { "hi", "20" };
List<object> objs = val.Select(x =>
{
    if (int.TryParse(x, out var intval))
       return (object)intval;
    else
       return (object)x;
}).ToList();

CodePudding user response:

If you just need to store all the results that you get to a single list without caring about the type then dont Parse to int type like

 for (int i = 0; i < val.Length; i  )
{
      //simply add the 
          obj.add(val[i]);
      
}

CodePudding user response:

Just use a List<object>. Every type ultimately derives from object:

List<object> obj = new List<object>();

string[] val = new string[] {"hi","20"};

for(int i = 0; i < val.Length; i  )
{
      if(int.TryParse(val[i], out var intval)
      {
          obj.add(intval);
      }
      else
      {
          obj.add(val[i]);
      }
}
  • Related