SetValue with generic type T - c#

I have this function:
the variable c obtains all the properties of my class <T>
in this case:
c ->
Id
Key
Value
public List<T> ReadStoreProceadure<T>(string storeName)
{
var result = new List<T>();
var instance = (T) Activator.CreateInstance(typeof (T), new object[] {});
var c = typeof (T);
var data = DataReader.ReadStoredProceadures(_factibilidad, storeName); // This part is returning verified data and it's ok
while (data.Read())
{
if (data.HasRows)
{
foreach (var item in c.GetProperties())
{
//item.SetValue(c, item.Name, null);
}
}
}
}
How I can add these values to my instance instance and add it to my result variable?
It's possible?

I've created an extension method for IDataReader that does essentially what I believe you're trying to do:
public static List<T> ToList<T>(this IDataReader dr) where T: new()
{
var col = new List<T>();
var type = typeof(T);
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
while (dr.Read())
{
var obj = new T();
for (int i = 0; i < dr.FieldCount; i++)
{
string fieldName = dr.GetName(i);
var prop = props.FirstOrDefault(x => x.Name.ToLower() == fieldName.ToLower());
if (prop != null)
{
if (dr[i] != DBNull.Value)
{
prop.SetValue(obj, dr[i], null);
}
}
}
col.Add(obj);
}
dr.Close();
return col;
}
However, you'll notice I've chosen to work the from the other way around. Instead of iterating the type's properties and fetching them from the DataReader, I iterate the DataReader columns and check for a matching property on the type. You should be able to quickly modify this to fit your data retrieval scheme.

Related

Get generic list from object (over reflection)

I query some data via reflection. The returned data type is System.data.datacolumn[] (variable "test"). I would like to convert it into a generic list (e.g. string List). Is that possible?
public IEnumerable<string> GetStringList(string property)
{
var test = GetPropertyValue(SomeObject, property);
// MAGIC //
return test;
}
public object GetPropertyValue(object obj, string propertyName)
{
var propertyNames = propertyName.Split('.');
foreach (var t in propertyNames)
{
if (obj != null)
{
var propertyInfo = obj.GetType().GetProperty(t);
obj = propertyInfo != null ? propertyInfo.GetValue(obj) : null;
}
}
return obj;
}
you can try this
if (test is IEnumerable) {
var values = test as IEnumerable;
//Method 1: convert to list
var asList = values.Cast<object>().ToList();
//Method 2: iterate to IEnumerable and add to List
var asList = new List<object>();
foreach (var value in values)
{
asList.Add(value);
}
}

Calling extension method from dynamic list

I am creating a type using reflection...
Type type = Type.GetType("Book");
I am then invoking a method dynamically...
MethodInfo method = typeof(DataHelper).GetMethod("GetTableData");
MethodInfo generic = method.MakeGenericMethod(type);
var parameters = new object[] {...};
dynamic data = generic.Invoke(this, parameters);
The method returns data, and looks like this...
public static IEnumerable<T> GetTableData<T>(parameters)
{
...
}
From the Dynamic data, I want to convert this to a list and call an extension method to convert the List into a DataTable.
I have tried the following, which fails when calling .ToDataTable:
var x = Enumerable.ToList(data);
x.ToDataTable().BulkCopyDataTable(settings, booName);
I have also tried:
var tl = GetTypedList(type);
foreach (var d in x)
{
tl.Add(d);
}
var y = tl.ToDataTable(); // compilaer error.
private static IList GetTypedList(Type t)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(t);
var instance = Activator.CreateInstance(constructedListType);
return (IList) instance;
}
The Extension method I am trying to call is:
public static DataTable ToDataTable<T>(this IList<T> data)
{
var properties = TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (var item in data)
{
var row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
Any pointers on where this is going wrong?

how can I get properties of a model with for loop [duplicate]

From the world of PHP I have decided to give C# a go. I've had a search but can't seem to find the answer of how to do the equivalent to this.
$object = new Object();
$vars = get_class_vars(get_class($object));
foreach($vars as $var)
{
doSomething($object->$var);
}
I basically have a List of an object. The object could be one of three different types and will have a set of public properties. I want to be able to get a list of the properties for the object, loop over them and then write them out to a file.
I'm thinking this has something to do with c# reflection but it's all new to me.
Any help would be greatly appreciated.
This should do it:
Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(myObject, null);
// Do something with propValue
}
void Test(){
var obj = new{a="aaa", b="bbb"};
var val_a = obj.GetValObjDy("a"); //="aaa"
var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
Yes, Reflection would be the way to go. First, you would get the Type that represents the type (at runtime) of the instance in the list. You can do this by calling the GetType method on Object. Because it is on the Object class, it's callable by every object in .NET, as all types derive from Object (well, technically, not everything, but that's not important here).
Once you have the Type instance, you can call the GetProperties method to get the PropertyInfo instances which represent the run-time informationa about the properties on the Type.
Note, you can use the overloads of GetProperties to help classify which properties you retrieve.
From there, you would just write the information out to a file.
Your code above, translated, would be:
// The instance, it can be of any type.
object o = <some object>;
// Get the type.
Type type = o.GetType();
// Get all public instance properties.
// Use the override if you want to classify
// which properties to return.
foreach (PropertyInfo info in type.GetProperties())
{
// Do something with the property info.
DoSomething(info);
}
Note that if you want method information or field information, you would have to call the one of the overloads of the GetMethods or GetFields methods respectively.
Also note, it's one thing to list out the members to a file, but you shouldn't use this information to drive logic based on property sets.
Assuming you have control over the implementations of the types, you should derive from a common base class or implement a common interface and make the calls on those (you can use the as or is operator to help determine which base class/interface you are working with at runtime).
However, if you don't control these type definitions and have to drive logic based on pattern matching, then that's fine.
well, in C# it's similar.
Here's one of the simplest examples (only for public properties):
var someObject = new { .../*properties*/... };
var propertyInfos = someObject.GetType().GetProperties();
foreach (PropertyInfo pInfo in propertyInfos)
{
string propertyName = pInfo.Name; //gets the name of the property
doSomething(pInfo.GetValue(someObject,null));
}
One line solution using Linq...
var obj = new {Property1 = 1, Property2 = 2};
var property1 = obj.GetType().GetProperties().First(o => o.Name == "Property1").GetValue(obj , null);
To get specific property value from property name
public class Bike{
public string Name {get;set;}
}
Bike b = new Bike {Name = "MyBike"};
to access property value of Name from string name of property
public object GetPropertyValue(string propertyName)
{
//returns value of property Name
return this.GetType().GetProperty(propertyName).GetValue(this, null);
}
You can use GetType - GetProperties - Linq Foreach:
obj.GetType().GetProperties().ToList().ForEach(p =>{
//p is each PropertyInfo
DoSomething(p);
});
Here's something I use to transform an IEnumerable<T> into a DataTable that contains columns representing T's properties, with one row for each item in the IEnumerable:
public static DataTable ToDataTable<T>(IEnumerable<T> items)
{
var table = CreateDataTableForPropertiesOfType<T>();
PropertyInfo[] piT = typeof(T).GetProperties();
foreach (var item in items)
{
var dr = table.NewRow();
for (int property = 0; property < table.Columns.Count; property++)
{
if (piT[property].CanRead)
{
var value = piT[property].GetValue(item, null);
if (piT[property].PropertyType.IsGenericType)
{
if (value == null)
{
dr[property] = DBNull.Value;
}
else
{
dr[property] = piT[property].GetValue(item, null);
}
}
else
{
dr[property] = piT[property].GetValue(item, null);
}
}
}
table.Rows.Add(dr);
}
return table;
}
public static DataTable CreateDataTableForPropertiesOfType<T>()
{
DataTable dt = new DataTable();
PropertyInfo[] piT = typeof(T).GetProperties();
foreach (PropertyInfo pi in piT)
{
Type propertyType = null;
if (pi.PropertyType.IsGenericType)
{
propertyType = pi.PropertyType.GetGenericArguments()[0];
}
else
{
propertyType = pi.PropertyType;
}
DataColumn dc = new DataColumn(pi.Name, propertyType);
if (pi.CanRead)
{
dt.Columns.Add(dc);
}
}
return dt;
}
This is "somewhat" overcomplicated, but it's actually quite good for seeing what the outcome is, as you can give it a List<T> of, for example:
public class Car
{
string Make { get; set; }
int YearOfManufacture {get; set; }
}
And you'll be returned a DataTable with the structure:
Make (string)
YearOfManufacture (int)
With one row per item in your List<Car>
This example trims all the string properties of an object.
public static void TrimModelProperties(Type type, object obj)
{
var propertyInfoArray = type.GetProperties(
BindingFlags.Public |
BindingFlags.Instance);
foreach (var propertyInfo in propertyInfoArray)
{
var propValue = propertyInfo.GetValue(obj, null);
if (propValue == null)
continue;
if (propValue.GetType().Name == "String")
propertyInfo.SetValue(
obj,
((string)propValue).Trim(),
null);
}
}
I haven't found this to work on, say Application objects. I have however had success with
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string rval = serializer.Serialize(myAppObj);
You can try this:
string[] arr = ((IEnumerable)obj).Cast<object>()
.Select(x => x.ToString())
.ToArray();
Once every array implements IEnumerable interface
public Dictionary<string, string> ToDictionary(object obj)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
Type objectType = obj.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(objectType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(obj, null);
dictionary.Add(prop.Name, propValue.ToString());
}
return dictionary;
}
/// get set value field in object to object new (two object field like )
public static void SetValueObjectToObject (object sourceObj , object resultObj)
{
IList<PropertyInfo> props = new List<PropertyInfo>(sourceObj.GetType().GetProperties());
foreach (PropertyInfo prop in props)
{
try
{
//get value in sourceObj
object propValue = prop.GetValue(sourceObj, null);
//set value in resultObj
PropertyInfo propResult = resultObj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
if (propResult != null && propResult.CanWrite)
{
propResult.SetValue(resultObj, propValue, null);
}
}
catch (Exception ex)
{
// do something with Ex
}
}
}

List of public Properties and their values [duplicate]

This question already has answers here:
How to get the list of properties of a class?
(11 answers)
Closed 9 years ago.
.Net 4.5 C#
To support an "Export to Excel" function for many classes, I need to be able to take a class, then from it get a list of the public property names (for the header) and the property values (for the rows)
Is there a way to reflect on an instance of a class and get the Property names and property values?
Here's a quick sample on how you can do this. Of course, you will need to update it so that you create/construct the CSV correctly, but this gives you an idea on how you can get the values you need.
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass()
{
Number = 1,
String = "test"
};
var properties = myClass.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var columnName = property.Name;
var value = myClass.GetType().GetProperty(columnName).GetValue(myClass, null);
Console.WriteLine(string.Format("{0} - {1}", columnName, value));
}
Console.ReadKey();
}
}
public class MyClass
{
public int Number { get; set; }
public string String { get; set; }
}
I actually recently created something like this for my job. I was writing a custom CSV serializer class to support an ill-conceived CSV file specification.
public CSVSerializer Serialize<T>(T data, Func<T, object> map)
{
if (map == null) throw new ArgumentNullException("map");
object mappedData = map(data);
if (mappedData == null) throw new NullReferenceException("Mapped data produced null value");
// Iterate over public members of `mappedData`
MemberInfo[] members = mappedData.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public);
List<string> values = new List<string>();
foreach (MemberInfo member in members)
{
// Skip events and methods
if (!(member is FieldInfo || member is PropertyInfo)) continue;
// Value of `mappedData`
object memberVal = MemberInfoValue(member, mappedData);
if (memberVal == null)
{
// If the actual value stored by `memberVal` is null, store string.Empty and continue
values.Add(string.Empty);
continue;
}
// Check if `memberVal` contains a member named "map"
MemberInfo[] maps = memberVal.GetType().GetMember("map");
MemberInfo memberMap = maps.Length > 0 ? maps[0] : null;
string val = MapToString(memberVal, o => o.ToString());
if (map != null) // map is present
{
// Get first property other than map
MemberInfo dataVal = memberVal.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public)
.Where(mi => mi is FieldInfo || mi is PropertyInfo)
.Except(new MemberInfo[] { memberMap })
.DefaultIfEmpty(memberMap)
.FirstOrDefault();
object tmp = MemberInfoValue(memberMap, memberVal);
if (dataVal == memberMap)
{
// map is only property, so serialize it
val = MapToString(tmp, o => o.ToString());
}
else
{
// try to serialize map(dataVal), or use empty string if it fails
Delegate dlg = tmp as Delegate;
if (dlg != null)
{
object param = MemberInfoValue(dataVal, memberVal);
try { val = MapToString(dlg, d => d.DynamicInvoke(param).ToString()); }
catch (Exception ex)
{
// exception should only occur with parameter count/type mismatch
throw new SerializationException(string.Format("Poorly formatted map function in {0}", member.Name), ex);
}
}
else
{
// map is not a delegate (!!)
throw new SerializationException(string.Format("map member in {0} is not a delegate type", member.Name));
}
}
}
// Handle quotes and the separator string
val = val.Trim('"');
if (val.Contains("\""))
{
val = val.Replace("\"", "\\\"");
}
if (val.Contains(Separator))
{
val = string.Format("\"{0}\"", val);
}
values.Add(val);
}
string line = string.Join(Separator, values);
Writer.WriteLine(line);
return this;
}
This function serializes the public fields and properties of data in the order they're defined; the names of those members are ignored.
If you're only interested in properties, you can use GetProperties instead of GetMembers (using PropertyInfo instead of MemberInfo). If you're not creating a CSV, you can obviously ignore the CSV file formatting portion.
MemberInfoValue(info, parent) returns ((FieldInfo)info).GetValue(parent) or ((PropertyInfo)info).GetValue(parent, null), as appropriate. MapToString is just a null-guard function.
The presence of the map parameter and hunting for a member named "map" is part of the necessities of my particular situation, although it may be useful to you. The mapping allows for things such as:
mySerializer.Serialize(myPersonObject,
p => new {
name = string.Format("{0}, {1}", p.LastName, p.FirstName),
address = p.address
});
I have an overload of Serialize which calls Serialize(data, d => d);. Hunting for the "map" member allows things like:
mySerializer.Serialize(new {
employeeID = new { val = myEmployeeObject.ID, map = d => d.ToUpperCase() },
employeeName = myEmployeeObject.Name
});
You could use some like this:
public static Dictionary<string, object> KeyValue(object obj)
{
return obj.GetType().GetProperties().ToDictionary(
m => m.Name,
m => m.GetValue(obj, new object[] { })
);
}

Convert DataSet to List

Here is my c# code
Employee objEmp = new Employee();
List<Employee> empList = new List<Employee>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
empList.Add(new Employee { Name = Convert.ToString(dr["Name"]), Age = Convert.ToInt32(dr["Age"]) });
}
It uses a loop to create a List from a dataset.Is there any direct method or shorter method or one line code to convert dataset to list
Try something like this:
var empList = ds.Tables[0].AsEnumerable()
.Select(dataRow => new Employee
{
Name = dataRow.Field<string>("Name")
}).ToList();
Here's extension method to convert DataTable to object list:
public static class Extensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item,day,null);
}
else
{
if(row[property.Name] == DBNull.Value)
property.SetValue(item, null, null);
else
{
if (Nullable.GetUnderlyingType(property.PropertyType) != null)
{
//nullable
object convertedValue = null;
try
{
convertedValue = System.Convert.ChangeType(row[property.Name], Nullable.GetUnderlyingType(property.PropertyType));
}
catch (Exception ex)
{
}
property.SetValue(item, convertedValue, null);
}
else
property.SetValue(item, row[property.Name], null);
}
}
}
return item;
}
}
usage:
List<Employee> lst = ds.Tables[0].ToList<Employee>();
#itay.b
CODE EXPLAINED:
We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.
The property values are picked from the row's matching column cell.
PS: class property name and table column names must be same
var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
Name = r.Field<string>("Name"),
Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable
Use the code below:
using Newtonsoft.Json;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(ds.Tables[0]);
Try this....modify the code as per your needs.
List<Employee> target = dt.AsEnumerable()
.Select(row => new Employee
{
Name = row.Field<string?>(0).GetValueOrDefault(),
Age= row.Field<int>(1)
}).ToList();
DataSet ds = new DataSet();
ds = obj.getXmlData();// get the multiple table in dataset.
Employee objEmp = new Employee ();// create the object of class Employee
List<Employee > empList = new List<Employee >();
int table = Convert.ToInt32(ds.Tables.Count);// count the number of table in dataset
for (int i = 1; i < table; i++)// set the table value in list one by one
{
foreach (DataRow dr in ds.Tables[i].Rows)
{
empList.Add(new Employee { Title1 = Convert.ToString(dr["Title"]), Hosting1 = Convert.ToString(dr["Hosting"]), Startdate1 = Convert.ToString(dr["Startdate"]), ExpDate1 = Convert.ToString(dr["ExpDate"]) });
}
}
dataGridView1.DataSource = empList;
Add a new class named as "Helper" and change the property of the class to "public static"
public static class Helper
{
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch
{
continue;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
}
and access this class in your code behind as like below
DataTable dtt = dsCallList.Tables[0];
List<CallAssignment> lstCallAssignement = dtt.DataTableToList<CallAssignment>();
Fill the dataset with data from, say a stored proc command
DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
adapter.Fill(ds);
Get The Schema,
string s = ds.GetXmlSchema();
save it to a file say: datasetSchema.xsd. Generate the C# classes for the Schema: (at the VS Command Prompt)
xsd datasetSchema.xsd /c
Now, when you need to convert the DataSet data to classes you can deserialize (the default name given to the generated root class is NewDataSet):
public static T Create<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xml))
{
T t = (T)serializer.Deserialize(reader);
reader.Close();
return t;
}
}
var xml = ds.GetXml();
var dataSetObjects = Create<NewDataSet>(xml);
I couldn't get Nitin Sawant's answer to work, but I was able to modify his code to work for me. Essentially I needed to use GetRuntimeFields instead of GetProperties. Here's what I ended up with:
public static class Extensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<FieldInfo> fields = typeof(T).GetRuntimeFields().ToList();
List<T> result = new List<T>();
if (row.Table.Columns.Contains(field.Name))
{
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, fields);
result.Add(item);
}
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<FieldInfo> fields) where T : new()
{
T item = new T();
foreach (var field in fields)
{
if (row[field.Name] == DBNull.Value)
field.SetValue(item, null);
else
field.SetValue(item, row[field.Name]);
}
return item;
}
}
Try the above which will run with any list type.
public DataTable ListToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
List<GSTEntity.gst_jobwork_to_mfgmaster> ListToGetJwToMfData = new List<GSTEntity.gst_jobwork_to_mfgmaster>();
DataSet getJwtMF = new DataSet();
getJwtMF = objgst_jobwork_to_mfgmaster_BLL.GetDataJobWorkToMfg(AssesseeId, PremiseId, Fyear, MonthId, out webex);
if(getJwtMF.Tables["gst_jobwork_to_mfgmaster"] != null)
{
ListToGetJwToMfData = (from master in getJwtMF.Tables["gst_jobwork_to_mfgmaster"].AsEnumerable() select new GSTEntity.gst_jobwork_to_mfgmaster { Partygstin = master.Field<string>("Partygstin"), Partystate =
master.Field<string>("Partystate"), NatureOfTransaction = master.Field<string>("NatureOfTransaction"), ChallanNo = master.Field<string>("ChallanNo"), ChallanDate=master.Field<int>("ChallanDate"), OtherJW_ChallanNo=master.Field<string>("OtherJW_ChallanNo"), OtherJW_ChallanDate = master.Field<int>("OtherJW_ChallanDate"),
OtherJW_GSTIN=master.Field<string>("OtherJW_GSTIN"),
OtherJW_State = master.Field<string>("OtherJW_State"),
InvoiceNo = master.Field<string>("InvoiceNo"),
InvoiceDate=master.Field<int>("InvoiceDate"),
Description =master.Field<string>("Description"),
UQC= master.Field<string>("UQC"),
qty=master.Field<decimal>("qty"),
TaxValue=master.Field<decimal>("TaxValue"),
Id=master.Field<int>("Id")
}).ToList();

Categories

Resources