0

My question is how do I have to make an object cast in a lambda expression from a List<ExportData> so that I can directly access the member AddressByte from class CyclicData?

Please do not describe any solutions without lambda, that I have already done. My question is if this is possible with lambda in one line of code?

    public class ExportData
    {
        public string Designation { get; set; }
    }

    public class StaticData : ExportData
    {
        public string Value { get; set; }
    }

    public class CyclicData : ExportData
    {
        public string Block { get; set; }
        public string Typ { get; set; }
        public string AddressByte { get; set; }
        public string AddressBit { get; set; }
    }

        public void getMemberFromList()
        {
            List<ExportData> list = new List<ExportData>();
            list.Add(new CyclicData());
            list.Add(new StaticData());
            list.Add(new StaticData());

            //   get addressByte form Cyclic object with one line of code
            string addressByte = list.Where(x => x.GetType() == typeof(CyclicData)).FirstOrDefault().AddressByte; 
            //-> does not work because of missing cast to CyclicData;
        }

Does anyone have any idea if and how this can be done?

3 Answers3

0

Try this:

        string addressByte = list.OfType<CyclicData>().FirstOrDefault().AddressByte; 

Assuming in the list there is always an instance of CyclicData, otherwise you'll get an exception.

Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
0

You can either use OfType (which filters the elements of list based on CyclicData) followed with FirstOrDefault:

string addressByte = list.OfType<CyclicData>().FirstOrDefault()?.AddressByte;

or use FirstOrDefault followed with an explicit cast.

string addressByte = ((CyclicData)list.FirstOrDefault(x => x is CyclicData))?.AddressByte; 
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

It's not a good practice to do this kind of inheritance[it clearly violates LSP rule] and writing code to the abstraction. To fool-proof this from a null exception

var addressByte = list.Where(x => x.GetType() == typeof(CyclicData)).FirstOrDefault();
if(addressByte !=null)
{
// do you logic here
}