wallah wallah - 5 days ago 4
C# Question

Getting value from IEnumerable collection

There are some problems here:

1) Firstly, I've a property in Class1

class Class1
{
IEnumerable itemSource;

public IEnumerable ItemSource
{
set { itemSource = value; }
get { return itemSource; }
}
}


2) a class named
TempClass


public class TempClass
{
int a;
public int A
{
set { a = value; }
get { return a; }
}

public TempClass() { }
public TempClass(int t) { A = t; }
}


3) In
static void Main(string[] args)
, I tried to this:

ObservableCollection<TempClass> test = new ObservableCollection<TempClass>
{
new TempClass(1),
new TempClass(2),
new TempClass(3)
}

Class1 class1 = new Class1();
class1.ItemSource = test;

foreach (var item in class1.ItemSource)
{
Console.WriteLine(item);
}


4) Then, the console shows this:

testSolution.TempClass
testSolution.TempClass
testSolution.TempClass


where
testSolution
is my solution name, so is a name of the namespace.

I want to get values: 1, 2, 3.

Here, what I want to make is a property and method that show values of any collection or list of any class type.

In this case, ItemSource property and method that has:

foreach (var item in class1.ItemSource)
{
Console.WriteLine(item);
}


How to do it?

Answer

This may need modification, am just laying out an idea on how to use reflection when the type and properties are unknown. I did not test this code,so feel free to modify

foreach(var objUnknown in ItemSource) {
    foreach(var prop in objUnknown.GetType().GetProperties()) {
        Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(objUnknown, null));
   }
}
Comments