chris
chris

Reputation: 107

Using Linq to access an objects properties within another object

I need to get a value from an object within an another object. My problem is I can't access any values from within the subobject, i always get the value of the object type itself.

Code where i'm accessing the object

var test = scheduledTask.Fields.Select(x => x.FieldValue);

This brings back in the results view

[0] 10111
[1] {ObjectType.Extension} 

I need to access the [1] element which contains the following properties (amongst others), and i need to access the DisplayName

{
DisplayName: "MainMenu",
CategoryId: -1,
Id: 433
}

ScheduledTask is

{
Fields: {Fields.Field[2]},
LastModifiedDate:null,
{Fields.Field[2]}
}

Upvotes: 0

Views: 1415

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

You don't need LINQ to access a specific index of an array.

string name = (scheduledTask.Fields[1].FieldValue as ObjectType.Extension)?.DisplayName;

Since the array contains values of different types I assume that we have an array of object. Therefore we must cast to the expected type to be able to access specific fields or properties.

In case the value is null or the type does not match as will yield null. The null-conditional operators ?. performs a member or element access operation only if an operand is non-null and otherwise return null.

If you don't know the index of the required value, you can query with

string name = (scheduledTask.Fields
    .Select(x => x.FieldValue)
    .OfType<ObjectType.Extension>()
    .FirstOrDefault()
)?.DisplayName;

If you are sure the required value is there and not null, you can drop the ?.

Upvotes: 2

gabriel.hayes
gabriel.hayes

Reputation: 2313

Assuming x.FieldValue is an object you could try casting to check if it is of type ObjectType.Extension:

var test = scheduledTask.Fields.Select(x => {
   var asExtension = x.FieldValue as ObjectType.Extension;
   if(asExtension != null) return asExtension.DisplayName;
   else return x.FieldValue;
});

ETA: The as operator is a sort of safe-cast that will return null if the runtime type of LHS argument doesn't match the static type identified by the RHS argument.

Upvotes: 0

Related Questions