0

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?

BlueCardinal
  • 153
  • 3
  • 12

1 Answers1

0

Do that on the server side without intermediate list. And actually you do not need LINQKit here.

public static string GetLongestString<TEntity>(Expression<Func<TEntity, string>> selector, DataSourceResult dataSourceResult) 
{
    var longestString = dataSourceResult.Data.Cast<TEntity>()
        .Select(selector)
        .OrderByDescending(i => i.Length)
        .FirstOrDefault();
        
    return longestString;
}
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32