I have a static method that takes an expression containing an entity and a property name of the entity, and a DataSourceResult (this is a Telerik UI for Blazor thing, but it's not important to understand Teleirk for this issue). The method returns the length of the longest string in a list of the specified property of the specified entity from a collection of data.
public static string GetLongestString<TEntity>(Expression<Func<TEntity, string>> selector, DataSourceResult dataSourceResult)
{
List<string> columns = dataSourceResult.Data.Cast<TEntity>()
.Select(i => selector.Invoke(i))
.ToList();
int longestString= columns
.OrderByDescending(i => i?.Length)
.FirstOrDefault()?.Length ?? 0;
}
It is called like this:
GetLongestString(((FirstEntity fe) => fe.SecondEntity.ThisProperty), result);
This works unless the related entity (SecondEntity) is null. How can I cleanly handle the case of when the related entity is null?