Home > Net >  Better way to get property from derived class
Better way to get property from derived class

Time:03-18

i have next class

public class MainClass
{
   public ClassA someProp { get; set; }
}

public class ClassA
{
   public virtual Type Types => Type.None;
}

public class ClassB:ClassA
{
   public override Type Types => Type.Default;
        
   public string FieldName { get; set; }
}

i want get FieldName from ClassB

var result = entities.Where(x => x.someProp != null).Select(x => x.someProp).ToList();

and than i get

var fields = (from ClassB in result select t.FieldName).ToList();

what is better way get FieldName from ClassB

I don't think this is the best solution. Maybe there are some best practices for my question?

CodePudding user response:

I've to filter the entities and get only those that are ClassB, then read the property as usual.

var values = entities
      .Select(mainClass => mainClass.SomeProp)
      .OfType<ClassB>()
      .Select(classB => classB.FieldName)

CodePudding user response:

You can try this:

var fields = entities
    .Where(item => item.someProp is ClassB)
    .Select(item => item.someProp)
    .Cast<ClassB>()
    .Select(item => item.FieldName).ToList();

CodePudding user response:

This is a shorter way, you can try cast ClassB from someProp:

var result = lst.Where(x => x.someProp != null).Select(x => (ClassB)x.someProp).Select(x => x.FieldName).ToList();
  • Related