Search code examples
c#linqgenericspropertyinfo

Generics - get properties LINQ


I have this class:

  private void Get_properties<T>(ObservableCollection<T> collection)
  {

     List<string> longest_values = new List<string>(); 

     var properties = typeof(T).GetProperties();

     foreach (var prop in properties)
     {
        var prop_value = collection.OrderByDescending(y=> prop.GetValue(y,null)).FirstOrDefault();
   
        longest_values.Add(prop_value);
      }

      //Now I want to do something with this List
      foreach (var item in longest_values)
      {
         //..
      }

    }

I'm trying to find values of each property in collection that has longest string value, by LINQ. How can I do that?


Solution

  • Update

    This will give you the "first of the longest string of all properties for each item"

    Or said a different way. This will iterate through the generic list, get all the properties and their values (of which are string), then get the first value (order by descending by length)

    var result = typeof(T)
       .GetProperties()
       .Where(x => x.PropertyType == typeof(string))
       .Select(prop => collection
          .Select(y => (string) prop.GetValue(y, null))
          .OrderByDescending(z => z.Length)
          .FirstOrDefault())
       .ToList();
    
    foreach (var item in result)
       Console.WriteLine(item);
    

    Original

    I think you were slightly off track with the OrderByDescending where you wanted a Select then orderby or orderby then select maybe? either way this will give you a list of values of properties in each object in the list

    var properties = typeof(T).GetProperties();
    
    foreach (var prop in properties)
    {
       var prop_values = collection.Select(y => prop.GetValue(y, null));
       Console.WriteLine(string.Join(",", prop_values)); 
    }