2

I have the following classes:

public class BaseClass() {}
public class Class1 : BaseClass {}
public class Class2 : BaseClass {}

public class BaseClassList : List<BaseClass> {}
public class Class1List : List<Class1> {}
public class Class2List : List<Class2> {}

The data is in JSON format are is loaded as a list of BaseClass objects. Once loaded and want to populate the specific lists with the relevant objects:

public void Setup()
{
    Class1List list1 = new Class1List();

    var query = from x in BaseClassList
                where x.Type = MyType.Class1
                select x;

    list1.AddRange(query);
}

However AddRange doesn't compile because I'm trying to added BaseClass objects to a Class1 list.

How can I successfully add the inherited classes?

1
  • 1
    BaseClassList is the name of a type - or do you have some property of that type too? It's also not clear why you have subclasses of List<T> at all - that's usually not a great idea, IME. Commented Feb 10, 2014 at 9:23

1 Answer 1

1

Try this code snippet,

public void Setup()
{
  Class1List list1 = new Class1List();

  var query = from x in BaseClassList
            where x.GetType() == typeof(Class1)
            select x as Class1;

  list1.AddRange(query);
}

The as operator casts your type BaseClassto type Class1

Reference: MSDN as Operator

As mentioned in a comment, you can do it a little bit more save with this snippet:

public void Setup()
{
  Class1List list1 = new Class1List();

  var query = from x in BaseClassList
        where x.GetType() == typeof(Class1)
        select x;

   foreach(var item in query){
      var temp = item as Class1;
      if(temp  != null)
         list1.Add(temp);
   }
}

After casting to Class1 you can check for null, as the asoperator returns null if unable to cast. I would prefer to make a type compare with where x.GetType() == typeof(Class1)

Sign up to request clarification or add additional context in comments.

7 Comments

Personally I'd use a cast rather than as - do you really want it to silently proceed (and add a null reference) if there's a non-Class1 element with a Type property of MyType.Class1?
The casting is always returning a null
@Ivan-MarkDebono why does it?
don't know. temp is always null.
So the objects are not of type Class1. What is MyType.Class1 ? Seems like a enum?!
|

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.