繁体   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