Reputation: 107
We have third party Test class,which has a method "Convert" which only accepts arrays of DataSample.
public class Test{
public class DataSample{
public int testVar{get;set;}
public int testVar2{get;set;}
}
//some methods
public static List<someType> Convert(DataSample[] data)
{
//execute some steps
}
}
We have a stored procedure which gives below output.it basically stored the object creation structure in col1 field
Id col1
1 new Test.DataSample{ testVar=24,testVar=11}
2 new Test.DataSample{ testVar=26,testVar=15}
3 null
4 null
5 new Test.DataSample{ testVar=28,testVar=11}
I am trying to create a class and invoke Convert method of Test class by providing array of DataSample type object. the Data type objects are stored on col1 field as above .
Public class ImplementTest{
public void CallConvert(){
var inputs = new Test.DataSample[] { };
// get the data from DB in list
List<object> InputList = new List<object>();
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.ReadAll_Input";
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
InputList.Add(dr["col1"]);
}
}
}
}
//remove null
InputList.RemoveAll(x => x == DBNull.Value);
//create an array of Test.DataSample type
??
//call third party class
var ourput = Test.Convert(inputs).ToArray();
}
}
How to pass all objects of InputList to inputs array so that it can passed to third party method Convert() which only accepts array of DataSample type ?
or is there a direct way we can create an array of DataSample type while fetching objects from stored procedure.
any hints on this please?
Thanks!
Upvotes: 0
Views: 257
Reputation: 77364
We have a stored procedure which gives below output
Wow... that's... interesting (1)
Whatever you are trying to do here is doomed to fail. Have your database do their job and deliver specific values, for example two columns, one with testVar and another with testVar2. Then build a new TestData
in your code and assign those two values.
If you cannot change the database interface (and in that case I strongly suggest to consider not working with whoever designed it for the next project) then at least take a Regular Expression, parse out the two values and then create the object yourself in your code.
There are two or three different ways to make this work, but all are more complicated than it's worth. Getting data from a database and building objects from it is really basic and you should not reinvent the black-hole-quantum-engine-anti-gravity-field when an already existing wheel is available.
(1) (I'll leave it at that to not violate the new CoC)
Upvotes: 1