0

LINQ newbie here

I am trying to get a value of a field - using a fieldName variable. If I do a watch on row[FieldName] I do get a value - but when I do it on the actual code it will not compile.

string fieldName = "awx_name"

List<awx_property> propertyQry = 
            (
                from property in crm.awx_propertyawx_properties
                where property.awx_propertyid == new Guid(id)
                select property
            ).ToList();

            foreach (awx_property row in propertyQry)
            {
//THIS DOES NOT WORK
fieldValue = row[fieldName];   
}

Thanks in advance. Alternatives would be welcome as well

2 Answers 2

1

You keep us guessing what you are trying to do here... You need to specify the types of the objects, so it's easy for us to understand and help. Anyway, I think you are trying to get an object based on the ID. Since you are getting by Id, my guess would be the return value is a single object.

var propertyObj =( from property in crm.awx_propertyawx_properties
                      where property.awx_propertyid == new Guid(id)
                      select property
                    ).SingleOrDefault();
   if(propertyObj != null) {
     fieldValue = propertyObj.GetType().GetProperty(fieldName).GetValue(propertyObj, null);
   }

Of course, you need to add validation to make sure you don't get null or any other error while accessing the property value.

Hope it helps.

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

Comments

0

What type is fieldValue? What does awx_property look like? This will only work is awx_property is a key/value collection. It its not, you could use reflection instead.

If it is a key/value collection you are probably missing a cast. (row[FieldName].ToString() or something) Also you are missing a semi-colon in the foreach block.

2 Comments

If I do row.awx_name it works fine. Maybe I should check out that reflection deal...
Microsoft.Xrm.Client.CrmEntity.this[string]' is inaccessible due to its protection level ==> this is the compile error I get

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.