how to read the values from the object variable in C# - c#

I need to read the values from a variable which is of type object for e..g.., i have a variable called result as:
object result= h[key];
h[key] is a hash table which returns 5 values to result variable. How do I read the 1st value to my local variable of type string in C# script in SSIS package?
I can see only GetType, Equals, ToString() options for result variable.
Any help please?
there is the sample:
there is a sample; public void SQLLoop()
{
string bp,ap,ep,s,vs;
LocationInfo info = new LocationInfo();
string connection = "Server=Sname;Database=Dname;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT Bp,Ap,EP,SL,VSr from Table1", conn);
SqlDataReader rs=sqlcmd.ExecuteReader();
while (rs.Read())
{
bp = rs.GetValue(0).ToString();
ap = rs.GetValue(1).ToString();
ep = rs.GetValue(2).ToString();
s = rs.GetValue(3).ToString();
vs = rs.GetValue(4).ToString();
info.loadLocationInfo(ap, bp, ep, s, vs);
h.Add(s, info);
}
conn.Close();
}
public class LocationInfo
{
String A;
String B;
String E;
String S;
String V;
int id;
public LocationInfo()
{
}
public void loadLocationInfo(String a,String b,String e,String s,String v)
{
A =a ;
B =b ;
E=e ;
S =s;
V = v;
}
}
now
public void fun1()
{
var result = (object )h[subject];
///read values from the hash table
}

Supposing you know the type of the result you can cast the objectvar result = (MyType) h[key]
EDIT: use this inside your function to get first value var result = ((LocationInfo) h[key]).A

Update:
Ok well you have the LocationInfo class so do something like this:
LocationInfo result = (LocationInfo)h[key];
Then just make some properties on the LocationInfo class to retrieve your strings.
Your probably need to cast the object that is in the hashtable. So something like:
result = (Type)h[key];
Here is an example of how it would work:
Person1 = new Person("David", "Burris");
Person2 = new Person("Johnny", "Carrol");
Person3 = new Person("Ji", "Jihuang");
//The Add method takes Key as the first parameter and Value as the second parameter.
try
{
MyTable.Add(Person1.Lname, Person1);
MyTable.Add(Person2.Lname, Person2);
MyTable.Add(Person3.Lname, Person3);
}
catch (ArgumentException ae)
{
MessageBox.Show("Duplicate Key");
MessageBox.Show(ae.Message);
}
So when you want to retrieve from the table you would do:
Person result = (Person)h[key];

You have to cast result to the class or interface you are expecting.
var result = (IExpectedObject)h[key];

Related

How to make a function that returns value from a list in C#

I have a list filled with objects. I have to make a function that when given a certain value of one of the class atributes, gives back another one. In my case, when you specify the "index", the function will return "standysp"(I'm sorry if I can't explain it to well). I need to make this function work but I don't even know when to start. Here is my Code:
using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
namespace dokselect
{
class PozycjaMagazynowa
{
public double standysp;
public string nazwagrupy;
public string index;
public string nazwadl;
}
class Program
{
public static void Main()
{
string conn = "SECRET";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "select STANMAG.standysp,GRUPAKART.nazwagrupy, KARTOTEKA.indeks, kartoteka.nazwadl FROM stanmag JOIN kartoteka using(ID_KARTOTEKA) JOIN wystgrkart using(ID_KARTOTEKA) JOIN grupakart using(ID_GRUPAKART) ORDER BY nazwagrupy;";
FbCommand myCommand = new FbCommand(sql, myConnection);
myConnection.Open();
myReader = myCommand.ExecuteReader();
List<PozycjaMagazynowa> lista1 = new List<PozycjaMagazynowa>();
double standysp;
string nazwagrupy;
string index;
string nazwadl;
while (myReader.Read())
{
standysp = Convert.ToDouble(myReader[0]);
nazwagrupy = myReader[1].ToString();
index = myReader[2].ToString();
nazwadl = myReader[3].ToString();
lista1.Add(new PozycjaMagazynowa { standysp = standysp, nazwagrupy = nazwagrupy, index = index, nazwadl = nazwadl });
}
myConnection.Close();
Console.WriteLine(lista1.Count);
//LISTA DONE
void wyswietl()
{
//????????
}
}
}
}
I'm not sure you're doing it the right way.
First the List you create is not accessible to others methods.
Secund, maybe the List is not appropriate and you may use a HashSet<T> or Dictionnary with your PozycjaMagazynowa class implementing IEqualityComparer
I used this method and it worked thank you for help:
double wyswietl()
{
string myIndex="WSIP_MAT_GIM";
var result = lista1.FirstOrDefault(lista1 => lista1.index == myIndex).standysp;
Console.WriteLine(myIndex + " Zostalo zwrocone przez funkcje");
Console.WriteLine(result + " - to stan dyspozycyjny pasujacy do podanego indexu");
return result;
}
wyswietl();

String interpolation: How do I make this function work with any type

This is a function to work with lists in string interpolation. It takes a List and an inner Func, and it appends the string result of the inner Func called for each member of the list, with a separator.
So the following builds a valid start of an Insert statement...
static void Main(string[] args)
{
var tableName = "customers";
var cols = new List<dynamic>
{
new { Name = "surname"},
new { Name = "firstname"},
new { Name = "dateOfBirth"}
};
Func<List<dynamic>, Func<dynamic, string>, string, string> ForEach = (list, func, separator) =>
{
var bldr = new StringBuilder();
var first = true;
foreach (var obj in list)
{
if (!first)
bldr.Append(separator);
first = false;
bldr.Append(func(obj));
}
return bldr.ToString();
};
var InsertStatement = $"Insert into { tableName } ( {ForEach(cols, col => col.Name, ", ")} )";
Console.WriteLine(InsertStatement);
Console.ReadLine();
}
Outputs...
Insert into customers ( surname, firstname, dateOfBirth )
It works for dynamic. How do I make it work for any type? The outer Func shouldn't care about the Type in the list, it just passes it through to the inner Func.
The .NET framework already gives you a generic function to achieve what you are trying to do String.Join and you can combine it with a LINQ Select statement, which will allow you to use a lambda on a generic type to select the property that you want to print. You can view the source code of these methods if you are interested as they are open source.
using System;
using System.Collections.Generic;
using System.Linq;
public class MyType
{
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
var tableName = "customers";
var cols = new List<MyType>
{
new MyType { Name = "surname"},
new MyType { Name = "firstname"},
new MyType { Name = "dateOfBirth"}
};
var InsertStatement = $"Insert into { tableName } ( {String.Join(", ", cols.Select(col => col.Name))} )";
Console.WriteLine(InsertStatement);
}
}
Replace dynamic with object, or TValue with a type constraint stipulating it must be a class (where TValue : class), and call obj.ToString() instead of just obj
However, this doesn't guarantee it would "work with any type" - for that you need to know that those types all follow a contract to output the desired column name as their string representation. To get more specificity, require that your accepted types must implement some interface eg IColumnName and put that interface into the type constraint instead
You can create the text easily like this:
var query = $"INSERT INTO {tableName}({string.Join(",", cols.Select(x=>x.Name))})";
However, if for learning purpose you are going to handle the case using a generic method, you can create a generic function like the following and then easily use a for loop and strip additional separator using TrimEnd, or as a better option, like String.Join implementation of .NET Framework get enumerator like this:
string Join<TItem>(
IEnumerable<TItem> items, Func<TItem, string> itemTextSelecor, string separator)
{
var en = items.GetEnumerator();
if (!en.MoveNext())
return String.Empty;
var builder = new StringBuilder();
if (en.Current != null)
builder.Append(itemTextSelecor(en.Current));
while (en.MoveNext())
{
builder.Append(separator);
if (en.Current != null)
builder.Append(itemTextSelecor(en.Current));
}
return builder.ToString();
}
And use it this way:
var tableName = "customers";
var cols = new[]
{
new { Name = "surname"},
new { Name = "firstname"},
new { Name = "dateOfBirth"}
};
var InsertStatement = $"INSERT INTO {tableName} ({Join(cols, col => col.Name, ", ")})"
+ $"VALUES({Join(cols, col => $"#{col.Name}", ", ")})";

C# string interpolation - is it possible to reflect internal intermediate structure?

Been using Dapper lately, so of course there is lots of code like:
var id = 123;
var s = "hola";
conn.Execute("update foo set bar = #a where id = #b", new { a = s, b = id })
This was also my first time with C# 6.0, so I've noticed similarity between the above and string interpolation:
$"update foo set bar = {s} where id = {id}"
However. this just works on plain strings, without any knowledge of parameters, escaping and so on. Would it be somehow possible to reflect on the intermediate structure generated by the compiler and then use it to properly set up the parameters? So, instead of resulting string, one could obtain something something that contains the string with holes, and the array of objects. Feels to me one could do quite a lot of things with such data.
Try something like this:
public static class DbExtensions
{
public static IDbCommand CreateCommand(this IDbConnection connection, FormattableString commandText)
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
if (commandText.ArgumentCount > 0)
{
var commandTextArguments = new string[commandText.ArgumentCount];
for (var i = 0; i < commandText.ArgumentCount; i++)
{
commandTextArguments[i] = "#p" + i.ToString();
command.AddParameter(commandTextArguments[i], commandText.GetArgument(i));
}
command.CommandText = string.Format(CultureInfo.InvariantCulture, commandText.Format, commandTextArguments);
}
else
{
command.CommandText = commandText.Format;
}
return command;
}
}

Dynamic Array to MS SQL Database

private void getRRvalue(string DELRRNO)
{
try {
DBSFCDataContext SFC = new DBSFCDataContext();
var query = (from i in SFC.POP10500s where i.POPRCTNM == DELRRNO select new { PONO = i.PONUMBER, DATEREC = i.DATERECD, VENDID = i.VENDORID, ITEMCODE = i.ITEMNMBR, QTYBAGS = i.QTYBAGS, QTYSHIP = i.QTYSHPPD, DEPT = i.TRXLOCTN });
foreach (var r in query)
{
string[] row = {
DELRRNO,
r.PONO,
Convert.ToDateTime(r.DATEREC).ToString(),
r.VENDID,
r.ITEMCODE,
r.QTYBAGS.ToString(),
r.QTYSHIP.ToString(),
r.DEPT
};
//glbVariables.getRRNO = ;
//glbVariables.getPONO = ;
//glbVariables.getRRdateRec = ;
//glbVariables.getVendID = ;
//glbVariables.getItemNO = ;
//glbVariables.getQtyBags = ;
//glbVariables.getQtyShipped = ;
//glbVariables.getLocnCode = ;
}
SFC.Connection.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message.ToString()); }
}
I'm new to C#.NET and I was just thinking if I could use a dynamic array like for this code above do I need to declare a global array like this --> "public static string[] row;" so I can use this array string in another form by calling it with the data that I have stored from this function, could this happen in c#?
I need help here please anyone that is good at arrays in c#...
To get you desired results, you will have to do little more work. I explain your solution using List.
First create a class for your one query result:
public class OneRowData
{
public string DELRRNO;
public string PONO;
public string DATEREC;
public string VENDID;
public string ITEMCODE;
public string QTYBAGS;
public string QTYSHIP;
public string DEPT;
}
In your given code, create a List of OneRowData type and make it public static to access it from outside the class as well:
public static List<OneRowData> QueryResults = new List<OneRowData>();
Now in your foreach loop, create an object of OneRowData, assing values to it and add it to the List:
foreach (var r in query)
{
OneRowData Obj = new OneRowData();
//assing values to them
Obj.DATEREC = Convert.ToDateTime(r.DATEREC).ToString();
Obj.DELRRNO = DELRRNO;
Obj.DEPT = r.DEPT;
Obj.ITEMCODE = r.ITEMCODE;
Obj.PONO = r.PONO;
Obj.QTYBAGS = r.QTYBAGS.ToString();
Obj.QTYSHIP = r.QTYSHIP.ToString();
Obj.VENDID = r.VENDID;
//then add the object to your list
QueryResults.Add(Obj);
}
Now you can simply call your List any where and fetch your data like this:
foreach (OneRowData Row in QueryResults)
{
//Row.DATEREC
//Row.DELRRNO
//call them like this and use as you need
}

How to access a string variable outside

public void Button1_Click(object sender, EventArgs e)
{
String a = DropDownList1.SelectedItem.Value;
String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');
String c = TextBox1.Text.PadLeft(5, '0').ToString();
String d = TextBox2.Text.ToString();
String digit = a + b + c + d;
try
{
OdbcConnection casetype = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
casetype.Open();
//************to get case type
string casetypequery = "select casename from casetype where skey=?";
//************to get case type
OdbcCommand casetypecmd = new OdbcCommand(casetypequery, casetype);
String casetypefromdropdown = DropDownList3.SelectedItem.ToString();
casetypecmd.Parameters.AddWithValue("?", casetypefromdropdown);
using (OdbcDataReader casetypeMyReader = casetypecmd.ExecuteReader())
{
while (casetypeMyReader.Read())
{
String casename = casetypeMyReader["casename"].ToString();
}
}
}
catch (Exception ewa)
{
Response.Write(ewa);
}
I am not able to access
String casename = casetypeMyReader["casename"].ToString();
which is inside while loop in my above code.
How can i access
'casename'
outside while loop?i want to use it to put the content in HtmlEditor(ajax)
If you want to access the variable outside the loop you need to declare it outside:
string casename = "some default value";
while (casetypeMyReader.Read())
{
casename = casetypeMyReader["casename"].ToString();
}
// You can access casename here and it's value will either be the default one
// if the reader returned no rows or the last row being read.
You could declare an Array or List of strings outside the loop, and save the casename values in that.
List<string> caseNames = new List<string>();
while (casetypeMyReader.Read())
{
caseNames.Add(casetypeMyReader["casename"].ToString());
}
Now they're all in the array and you can access it wherever.
If there are duplicates, and you need unique values, you can do caseNames.Distinct().ToList() afterwards.

Categories