2016-03-02 211 views
1

我有一个方法,我传递一个列表,然后在列表中进行排序。如何传递属性和sortorder作为排序列表的参数方法

类型ChartItemData包括如AverageProportionHighScoreProportionLowScore的属性。根据方法的使用情况,我需要在不同属性的方法内对列表进行排序,以及升序或降序。

如何在参数列表中指定要排序的属性以及要使用的排序顺序?

我想我可以设置SortDirection的Enum,但我仍然需要找出如何传递属性进行排序。这里有一些伪代码来说明我在使用List.OrderBy之后。如果这样做更有意义,我也可以使用List.Sort方法对列表进行排序。

public enum SortDirection { Ascending, Descending } 

public void myMethod(List<ChartItemData> myList, "parameter propertyToSortOn", 
    SortDirection direction) 
{ 
    if (direction == SortDirection.Ascending) 
     var sorted = ChartData.OrderBy(x => x."propertyToSortOn").ToList(); 
    else 
     var sorted = ChartData.OrderByDescending(x => x."propertyToSortOn").ToList(); 
} 
+0

尝试使用反射基于字符串传递,以获得正确的属性:https://msdn.microsoft.com/en- us/library/kz0a8sxy(v = vs.110).aspx –

+0

你可以定义你自己的比较器,看这个链接:http://stackoverflow.com/questions/12753762/linq-syntax-for-orderby-with-custom- comparert – Aliz

回答

2

会是这样的工作?它允许你引用属性来通过第二个方法参数(lambda)进行排序。否则,你几乎会坚持反思。

public class ChartItemData 
    { 
     public double Average { get; set; } 
     public double HighScore { get; set; } 
     public double LowScore { get; set; } 

     public string Name { get; set; } 
    } 

    class Program 
    { 
     public enum SortDirection { Ascending, Descending } 

     public void myMethod<T>(List<ChartItemData> myList, Func<ChartItemData, T> selector, SortDirection direction) 
     { 
      List<ChartItemData> sorted = null; 

      if (direction == SortDirection.Ascending) 
      { 
       sorted = myList.OrderBy(selector).ToList(); 
      } 
      else 
      { 
       sorted = myList.OrderByDescending(selector).ToList(); 
      } 

      myList.Clear(); 
      myList.AddRange(sorted); 
     } 

     public void usage() 
     { 
      List<ChartItemData> items = new List<ChartItemData>(); 

      myMethod(items, x => x.Average, SortDirection.Ascending); 
      myMethod(items, x => x.Name, SortDirection.Ascending); 
     } 
+0

谢谢,这看起来不错 - 而且我也很高兴能够尝试并了解“方法”签名,这是我之前没有用过的签名。 –

1

我会说最简单的方法是use reflection to get the PropertyInfo from the name provided

然后,您可以use that PropertyInfo to get the value from each value within the list以按以下方式列表:

public List<ChartItemData> myMethod(List<ChartItemData> myList, string propName, SortDirection direction) 
{ 
    var desiredProperty = typeof(ChartItemData).GetProperty(propName, BindingFlags.Public | BindingFlags.Instance); 

    if (direction == SortDirection.Ascending) 
     return myList.OrderBy(x => desiredProperty.GetValue(x)).ToList(); 
    else 
     return myList.OrderByDescending(x => desiredProperty.GetValue(x)).ToList(); 
} 
+0

非常好,这将工作。我会在一些情况下尝试。但是,如果我理解正确,在这里我需要传递属性名称作为硬编码,所以大概如果我更改属性名称,我必须然后更新字符串代码?我假设没有Object.Property.PropertyNameToString()? –

相关问题