-2

I have a list like this:

List<object> myList=new List<object>();
myLists items:
 obj1 
 obj2 
 obj3

and have a class:

Class MyClass
{
   public object cObj1{get;set;}
   public object cObj2{get;set;}
   public object cObj3{get;set;}
}

and now i need to copy myList into an object of MyClass:

 myClass.cObj1=myList[0];
 myClass.cObj2=myList[1];
 myClass.cObj3=myList[2];
mahboub_mo
  • 2,908
  • 6
  • 32
  • 72
  • 1
    What's wrong with what you have done now? What are you trying to achieve exactly? – nawfal Dec 15 '12 at 06:13
  • http://stackoverflow.com/questions/5675336/linq-pivot-with-dynamic-columns – Mohsen Dec 15 '12 at 06:13
  • It seems you just need pivot , take a look at this : http://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq – Mohsen Dec 15 '12 at 06:17
  • @ nawfal: In real case i don't know how many items are on `MyList`(i have a maximum point),so i need to check if index exists first,it becomes a dirty code! – mahboub_mo Dec 15 '12 at 06:44
  • are you trying to add the items from `myList` to `MyClass`? – spajce Dec 15 '12 at 07:20
  • If you don't know how many items in the list, so you can't decide how many properties you should create in MyClass?? so can you please tell us what exactly you are trying to do! – Nour Dec 15 '12 at 07:24
  • you could inherit the `MyClass` for another instance to create a `List` so you could simply solve your problem :) – spajce Dec 15 '12 at 07:29
  • @ Nour Sabouny : As i told Nawfal,i have a maximum point! – mahboub_mo Dec 15 '12 at 08:11
  • @ spajce: Thankyou,but i want bind it to WpfDataGrid.ItemsSource and need to know Properties names! – mahboub_mo Dec 15 '12 at 08:13

3 Answers3

2

you can try this:

        MyClass s = new MyClass();
        int j = 0;
        s.GetType().GetProperties().ToList().ForEach(x => { x.SetValue(s, mylist[j++], null); });
bala
  • 36
  • 2
1

if you can differentiate between list item:

var result = new MyClass(){
    cObj1 = myList.Where(item=> item.SomeProprty == someValue).FirstOrDefault()
   ,cObj2 = myList.Where(item=> item.SomeProprty == someValue).FirstOrDefault()
   ,cObj3 = myList.Where(item=> item.SomeProprty == someValue).FirstOrDefault()
};
Nour
  • 5,252
  • 3
  • 41
  • 66
0
MyClass s = new MyClass();           
PropertyInfo[] p = s.GetType().GetProperties();
int i=0;
foreach (PropertyInfo prop in p)
{
    prop.SetValue(s, mylist[i++], null); 
}

when you could not differentiate the items and does not know how many items in list , you can achieve it through this way.

The following code snippet is not working

var v = p.Select(obj=> { obj.SetValue(s, mylist[i], null); i++; });

you can refer this.

Community
  • 1
  • 1
user1905861
  • 9
  • 1
  • 3