Assign any IEnumerable to object property - c#

I have a list of objects created using reflection, they are all the same type, however the type is unknown at compile time.
I'm trying to figure out the best way of assigning this list (also using reflection) to an object property which could be any IEnumerable.
List<object>
ArrayList
Custom : List<object>
The only approach I have is to assume the property is an ICollection then loop through the IEnumerable and add each item. (See below, where list is the IEnumerable source, key is the string name of the object property and result is the object itself)
foreach (object item in list) {
PropertyInfo prop = result.GetType().GetProperty(key);
var collection = prop.GetValue(result, null);
Type collectionType = collection.GetType();
MethodInfo add = collectionType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
add.Invoke(collection, new object[] { item });
}

Since you say the data is homogeous, I would suggest typing it as closely as you can; so assuming list is non-empty, list[0].GetType() will tell you the Type of all the data. At this point, you could do:
IList typedList = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(itemType));
...
foreach(var item in list) typedListAdd(item);
or you could use an array:
Array arr = Array.CreateInstance(itemCount, list.Count);
list.CopyTo(arr, 0);
Either of which will give you a well typed list, which tends to work much better for most purposes (data-binding, serialization, or just reflection).
If list is not actually a list, but is just IEnumerable, then you can basically still do the same thing, but simply defer the creation until the first item:
IList typedList = null;
foreach(object item in list) {
if(typedList == null) {
typedList = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(item.GetType()));
}
typedList.Add(item);
}
return typedList ?? new object[0];

There are a couple of ways that you can add items to an existing collection of not known type:
Check for the IList interface or check of an Add method as a fallback;
public void Add(object obj, string propertyName, IEnumerable enumerable)
{
Action<object> add;
PropertyInfo prop = obj.GetType().GetProperty(propertyName);
var property = prop.GetValue(obj, null);
var collection = property as IList;
// Check for IList
if(collection != null)
{
add = item => collection.Add(item);
}
// Try to get an Add method as fallback
else
{
var objType = obj.GetType();
var addMethod = objType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
// Property doesn't support Adding
if(addMethod == null) throw new InvalidOperationException("Method Add does not exist on class " + objType.Name);
add = item => addMethod.Invoke(obj, new object[] { item });
}
foreach (var item in enumerable)
{
add(item);
}
}
I would probably go with Marc's way since it's more type safe.
public class Foo
{
public Foo()
{
Bar = new List<string>();
}
public List<string> Bar { get; set; }
public string Qux { get; set; }
}
var result = new Foo();
var key = "Bar";
var list = new List<object> { "A", "B" };
Add(result, key, list);

Related

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
}
}
}

How can I filter generic list by reflection in c#

I have a generic list. I have to filter the list based on the value of the property of list item. Item type is not known until runtime.
I have to find the item type by reflection and then need to filter.
Please help me by any idea or example
Thanks.
I Hope this help
pass any list, and specify a property name, and a filter method
private IList FilterList(IList list, string propName, Predicate<object> filterMethod) {
var result = new List<object>();
foreach (var item in list) {
var value = item.GetType().GetProperty(propName).GetValue(item);
if (filterMethod(value)) {
result.Add(item);
}
}
return result;
}
Example :
var result = FilterList(list, "Age", age => (int)age >= 18);
you can develop it and make it fully dynamic
If the list is generic you should know at least a base type at compile time.
If the base type contains the property - just use it.
If only some of the subtypes(ideally one) contain the property you're interested in you can do a cast on the list and then use your property.
list.Cast<Derived>().Select(i => i.Property == "val");
If that is not ok(say the type of the list has many derived types that contain the property and others that do not), you can use dynamic with a try/catch block.
list.Select(i => {
try
{
dynamic item = i;
return item.Prop == "value";
}
catch(RuntimeBinderException) //this type doesn't contain the property
{
return false;
}
});
Try this. It can determine whether a List is a list of some specified type. Based on that you should be able to filter for any specific type.
public class TypeA
{ }
public class TypeB
{ }
public class GenericFilter
{
public bool IsOfType<T>(IEnumerable<dynamic> objectToInspect)
{
var genericType = objectToInspect.GetType().GenericTypeArguments[0];
return genericType == typeof(T);
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void IdentifiesExpectedType()
{
var classToInspect = new List<TypeA>();
var filter = new GenericFilter();
Assert.IsTrue(filter.IsOfType<TypeA>(classToInspect));
}
[TestMethod]
public void RejectsNonMatchingType()
{
var classToInspect = new List<TypeA>();
var filter = new GenericFilter();
Assert.IsFalse(filter.IsOfType<TypeB>(classToInspect));
}
}
This works just as well:
public bool IsOfType<T>(IEnumerable<dynamic> listToFilter)
{
return (listToFilter as IEnumerable<T>) != null;
}
This will take a list of lists and group them into a Dictionary<Type, List<List<dynamic>> where all of the lists for each key are of that type. That way you can select lists of type T just by retrieving them from the dictionary.
public Dictionary<Type, List<List<dynamic>>> GroupListsByType(List<List<dynamic>> lists)
{
var types = lists.Select(list => list.GetType().GenericTypeArguments[0]).Distinct().ToList();
var grouped = new Dictionary<Type, List<List<dynamic>>>();
types.ForEach(type =>
{
grouped.Add(type, new List<List<dynamic>>());
grouped[type].AddRange(lists.Where(list=>list.GetType().GenericTypeArguments[0] == type));
});
return grouped;
}
(I'm not questioning the "why." I don't know if I would recommend this, but it's interesting to write.)

Accessing Properties of items contained in an IEnumerable

Sorry if the title is misleading, you can correct if you have an idea what I'm trying to say.
I have a function which takes in an IEnumberable. The IEnumerable is type annonymous.
My Function is below
public void AddToCollection_Short(IEnumerable query)
{
List<object> list = new List<object>();
foreach (var item in query)
{
var obj = new object();
var date = item.Date.ToShortDateString();
obj = new { date, item.Id, item.Subject };
list.Add(obj);
}
AllQueries = list;
OnPropertyChanged("AllQueries");
}
It doesn't recognize the suffix such as .Id, .Date, .Subject. May I ask what approach I should take to fix this. Is there something like IEnumerable<Datetime Date, int Id, string Subject> query
If you know the type, you can cast your objects
foreach (var item in query.Cast<YourType>())
If you don't know then you can use dynamic feature.And you can access your properties without a compile time error but if you try to access a property or a method which is not exist you will get a RuntimeBinderException in runtime.
foreach (dynamic item in query)
{
...
}
You could use (in C# 4.0 and higher) the dynamic keyword or update the signature to AddToCollection_Short.
public void AddToCollection_Short(IEnumerable query)
{
List<object> list = new List<object>();
foreach (dynamic item in query)
{
var obj = new object();
var date = item.Date.ToShortDateString();
obj = new { date, item.Id, item.Subject };
list.Add(obj);
}
AllQueries = list;
OnPropertyChanged("AllQueries");
}
You should be able to specify a type parameter to your method.
public void AddToCollection_Short<T>(IEnumerable<T> query) where T : IAmCommonInterface
{
List<object> list = new List<object>();
foreach (T item in query)
{
var obj = new object();
var date = item.Date.ToShortDateString();
obj = new { date, item.Id, item.Subject };
list.Add(obj);
}
AllQueries = list;
OnPropertyChanged("AllQueries");
}
and your common interface for your type paramater would have all the properties that you want on it.
The advantage to this is the compiler will tell you when you try to use this on an Enumerable that doesn't have those properties.

Generic SqlDataReader to Object Mapper

I'm trying to build a generic mapper which will convert the results of a SqlDataReader into a class object.
Here is the basic structure for my code:
public interface IObjectCore
{
//contains properties for each of my objects
}
public class ObjectMapper<T> where T : IObjectCore, new()
{
public List<T> MapReaderToObjectList(SqlDataReader reader)
{
var resultList = new List<T>();
while (reader.Read())
{
var item = new T();
Type t = item.GetType();
foreach (PropertyInfo property in t.GetProperties())
{
Type type = property.PropertyType;
string readerValue = string.Empty;
if (reader[property.Name] != DBNull.Value)
{
readerValue = reader[property.Name].ToString();
}
if (!string.IsNullOrEmpty(readerValue))
{
property.SetValue(property, readerValue.To(type), null);
}
}
}
return resultList;
}
}
public static class TypeCaster
{
public static object To(this string value, Type t)
{
return Convert.ChangeType(value, t);
}
}
For the most part it seems to work, but as soon as it tries to set the value of the property, I get the following error:
Object does not match target type
on the line where I have property.SetValue.
I have tried everything and I don't see what I might be doing wrong.
You are trying to set the value of the property you are looping through, I think your intent is to set the value of the newly created item that you have because that is going to match the Type that you are passing it based on item.GetType()
var item = new T();
//other code
property.SetValue(item , readerValue.To(type), null);
instead of
property.SetValue(property, readerValue.To(type), null);
Also per comment, make sure you have:
resultList.Add(item);
Looks like this part is wrong:
property.SetValue(property, readerValue.To(type), null);
Are you certain you want to apply SetValue by passing property to it?
Looks to me you should pass the object of type T which is item.
This then becomes:
property.SetValue(item, readerValue.To(type), null);

How to convert IEnumerable to ObservableCollection?

How to convert IEnumerable to ObservableCollection?
As per the MSDN
var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable);
This will make a shallow copy of the current IEnumerable and turn it in to a ObservableCollection.
If you're working with non-generic IEnumerable you can do it this way:
public ObservableCollection<object> Convert(IEnumerable original)
{
return new ObservableCollection<object>(original.Cast<object>());
}
If you're working with generic IEnumerable<T> you can do it this way:
public ObservableCollection<T> Convert<T>(IEnumerable<T> original)
{
return new ObservableCollection<T>(original);
}
If you're working with non-generic IEnumerable but know the type of elements, you can do it this way:
public ObservableCollection<T> Convert<T>(IEnumerable original)
{
return new ObservableCollection<T>(original.Cast<T>());
}
To make things even more simple you can create an Extension method out of it.
public static class Extensions
{
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> col)
{
return new ObservableCollection<T>(col);
}
}
Then you can call the method on every IEnumerable
var lst = new List<object>().ToObservableCollection();
ObservableCollection<decimal> distinctPkgIdList = new ObservableCollection<decimal>();
guPackgIds.Distinct().ToList().ForEach(i => distinctPkgIdList.Add(i));
// distinctPkgIdList - ObservableCollection
// guPackgIds.Distinct() - IEnumerable
The C# Function to Convert the IEnumerable to ObservableCollection
private ObservableCollection<dynamic> IEnumeratorToObservableCollection(IEnumerable source)
{
ObservableCollection<dynamic> SourceCollection = new ObservableCollection<dynamic>();
IEnumerator enumItem = source.GetEnumerator();
var gType = source.GetType();
string collectionFullName = gType.FullName;
Type[] genericTypes = gType.GetGenericArguments();
string className = genericTypes[0].Name;
string classFullName = genericTypes[0].FullName;
string assName = (classFullName.Split('.'))[0];
// Get the type contained in the name string
Type type = Type.GetType(classFullName, true);
// create an instance of that type
object instance = Activator.CreateInstance(type);
List<PropertyInfo> oProperty = instance.GetType().GetProperties().ToList();
while (enumItem.MoveNext())
{
Object instanceInner = Activator.CreateInstance(type);
var x = enumItem.Current;
foreach (var item in oProperty)
{
if (x.GetType().GetProperty(item.Name) != null)
{
var propertyValue = x.GetType().GetProperty(item.Name).GetValue(x, null);
if (propertyValue != null)
{
PropertyInfo prop = type.GetProperty(item.Name);
prop.SetValue(instanceInner, propertyValue, null);
}
}
}
SourceCollection.Add(instanceInner);
}
return SourceCollection;
}

Categories

Resources