簡體   English   中英

如何使用 C# 中的 For 循環引用通用 Object 中的屬性

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

我正在嘗試創建一個通用方法,用於根據給出的任何屬性值對對象列表進行排序。 例如,對於客戶列表,我可能希望按string值的客戶名稱或int值的客戶 ID 進行排序。

出於這個問題的目的,我將使用Customer class ,它包含兩個屬性NameId和一個返回Customer硬編碼集合的方法CollectionData()

該方法應返回List<Customer>的排序集合。

該方法接收兩個參數List<Customer>nameof(Customer.Name)nameof(Customer.Id)

目前我正在調用如下方法,但願意接受改進建議:

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

這是我的SortObjectList方法

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

因為我的方法是通用的,所以我不確定如何在循環中使用propertyName

例如。

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)
        */
   }


}

如何引用 object 的屬性名稱?

注意:我需要使用索引來引用和迭代集合,因此無法按照 Stackoverflow 上發布的先前問題/答案使用 foreach 循環。

我需要比較當前propertyName[i]和當前propertyName值 +1 [i + 1]

例如,為了比較 integer 值,我想使用類似的東西

// 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
}

我希望這一切都有意義? 關於如何實現這一目標的任何想法?

一種選擇是使用 LINQ OrderBy https://docs.microsoft.com/en-us/dotnet/api/system.linq-5.enumerable.

var enumerableOrderedByName = Customers.OrderBy(x => x.Name);
var enumerableOrderedById = Customers.OrderBy(x => x.Id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM