2

I have an object model like this:

public class MyClass
{
  int TheProp {get;set;}
  List<Object1> TheListOfObject1 {get;set;}
  List<Object2> TheListOfObject2 {get;set;}
  List<Object3> TheListOfObject3 {get;set;}  
  List<Object4> TheListOfObject4 {get;set;}
}

Now some the the nested objects contain a property called MyField and some of the lists might have objects in them and some don't.

I'm looking to loop through every list and if the objects in the list contain the property MyField then set that property to 1.

What's the best way to do this? I could hard-code the loop and only loop through the lists for which I know there's the property I'm looking for and then test if the list has a count > 0 but if I then add another list of nested object I'd have to rewrite that part too. What's a more general way to do it?

Thanks.

2
  • What are Object1, Object2, Object3? Are these different classes? How can the lists of different types contain a specific property? Commented Dec 21, 2011 at 23:16
  • @Paul: yes, they're different classes. Some contain the userID and that's what I'm looking to add to these objects. Commented Dec 21, 2011 at 23:43

2 Answers 2

4

Either use reflection or write an interface containing that property

public interface IProperty {
    int Prop { get; set; }
}

and implement it in all your classes which have that property. Then you can use

foreach (var obj in myList.OfType<IProperty>()) {
    obj.Prop = 1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best practice.I was writing the same :) sehr gut
1

The question here is: Do you really need to have different lists? Let us assume that your ObjectX classes all derive from a common base class BaseObject.

class BaseClass {
    int Prop { get; set; }
    // possibly other members here
}

class Object1 : BaseClass {
}

class Object2 : BaseClass {
}

// And so on

Then you could either add all your objects to the same list:

List<BaseClass> list = new List<BaseClass>();
list.Add(new Object1());
list.Add(new Object2());

Or you could have a list of lists:

List<List<BaseClass>> lists = new List<List<BaseClass>>();
lists.Add(new List<BaseClass>());
lists.Add(new List<BaseClass>());

lists[0].Add(new Object1());
lists[1].Add(new Object2());

Using nested loops you can access all your objects at once:

foreach (List<BaseClass> lst in lists) {
    foreach (BaseClass obj in lst) {
        if (obj != null) {
            obj.Prop = 1;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.