I have a this get setter class:
public class GetSetterClass
{
[Required]
[DisplayName("Some_Display_Name_1")]
public int SomeProperty1 { get; set; }
[Required]
public string SomeProperty2 { get; set; }
}
After extracting the property info of the class, I want to extract a property based on:
DisplayName
- If no
DisplayName
attribute present, I want to get property info byDataFieldName
This is the code I already have:
string testString1 = "Some_Display_Name_1";
string testString2 = "SomeProperty2";
string testString = testString1;
prop = props.FirstOrDefault(t => ((
t.PropertyInfo.GetCustomAttributes<DisplayNameAttribute>()?.FirstOrDefault() as DisplayNameAttribute)
.DisplayName
.Equals(testString , StringComparison.OrdinalIgnoreCase) ||
t.DataFieldName.Equals(testString , StringComparison.OrdinalIgnoreCase)
))?.PropertyInfo;
Here is the outcome:
- The property with the
DisplayName
is successfully extracted. - However, when I set
teststring="SomeProperty2";
I get a null reference exception.
Please advise.
CodePudding user response:
Can you check this ?
Its look like DisplayName is null for SomeProperty2
props.FirstOrDefault(t => ((
t.PropertyInfo.GetCustomAttributes<DisplayNameAttribute>()?.FirstOrDefault() as DisplayNameAttribute)
.DisplayName
?.Equals(testString , StringComparison.OrdinalIgnoreCase) ||
t.DataFieldName.Equals(testString , StringComparison.OrdinalIgnoreCase)
))?.PropertyInfo;
CodePudding user response:
I found the answer after exploring LINQ more. here it is
prop = props.FindAll( p => p.PropertyInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true).Any())
.FirstOrDefault(p => p.PropertyInfo.GetCustomAttributes(typeof(DisplayNameAttribute), true)
.Cast<DisplayNameAttribute>()
.Any(a => a.DisplayName.Equals(teststring, StringComparison.OrdinalIgnoreCase)))?.PropertyInfo ??
props.FirstOrDefault(t => t.DataFieldName.Equals(teststring, StringComparison.OrdinalIgnoreCase))?.PropertyInfo;