How to reference a Property in a Generic Object using a For Loop in C#

Viewed 34

I am trying to create a generic method for sorting a List of objects based on whatever property value was given. e.g. For a customer list I may want to sort by the customer name which is a string value or the customer ID which is an int value.

For the purposes of this question I will use a Customer class that contains two properties Name, Id and a method CollectionData() that returns a hard coded collection of Customers.

The method should return a sorted collection of List<Customer>.

The method receives two parameters List<Customer> and nameof(Customer.Name) or nameof(Customer.Id)

Currently I am calling the method as below but am open to suggestions for improvements:

SortObjectList(Customer.CollectionData(), nameof(Customer.Name));

Here is my SortObjectList method

public static List<TObjectType> SortObjectList<TObjectType, TNameOfProperty>(List<TObjectType> objectList, TNameOfProperty propertyName)
{
   // Code for sorting algorithm here
}

Because my method is generic I am unsure of how use propertyName in a loop.

For example.

public static List<TObjectType> SortObjectList<TObjectType, TNameOfProperty>(List<TObjectType> objectList, TNameOfProperty propertyName)
{

   int listCount = objectList.Count;
     
   for (int i = 0; i < listCount; i++)
   {

       // Get the current object
       TObjectType currentObject = objectList[i];

       /* 
        Here I would like to access the propertyName value
        e.g. currentObject.propertyName  (I am aware this will not work but using this to portray my concept)
        */
   }


}

How am I able to reference a property name for an object?

NOTE: I need to use an index to reference and iterate over the collection and therefore am unable to use a foreach loop as per previous questions/answers posted on Stackoverflow.

I need to compare the current propertyName value [i] and the current propertyName value +1 [i + 1]

e.g. For comparing an integer value I would like to use something like

// Compare Integer Value
if(currentObject[i].propertyName == currentObject[i+1].propertyName)
{
   // Code if statement true
}

// Compare String Value
if (currentObject[i].propertyName.CompareTo(currentObject[i+1].propertyName) > 0)
{
    // Code if statement true
}

I hope this all makes sense? Any ideas on how I can achieve this?

1 Answers
Related