【问题标题】:Order by anonymous method通过匿名方法订购
【发布时间】:2013-02-19 07:01:25
【问题描述】:

关于How to cast while Sorting?,我尝试了以下答案之一。

vehicleList.OrderBy(c=>
{
    Car car = c as Car;
    if (car != null)
        return car.ModelName
    else
        return "";
}

但它给出了编译器错误:

方法的类型参数 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' 不能从用法中推断出来。尝试 明确指定类型参数。

这有什么问题?如何纠正?

我尝试实现的目标如下:

  • 如果对象是 Car 类型,则按 ModelName 排序
  • 否则,如果对象 ID 为 Train 类型,则为 TrainName。

【问题讨论】:

  • 你的代码是Contact,但你说的是CarTrainuiItems 是什么?
  • 对不起,我放了实际的程序代码......我使用车辆,因为它很容易理解......现在将更正。谢谢
  • vehicleList的类型是什么?通常你不应该得到这个错误。

标签: c# .net linq compiler-errors sql-order-by


【解决方案1】:

这解决了错误:

var sortedVehicles = vehicleList.OrderBy<Vehicle, string>(c=>
    {
        ...
    });

【讨论】:

    【解决方案2】:

    你可以像这样实现一个比较器:

    var sorted = uiItems.OrderBy(x => x.Contact, new YourComparer ());
    
    public class YourComparer : IComparer<Contact>
    {
        public int Compare(Contact? x, Contact? y)
        {
            if (x == y)
                return 0;
            if (x == null)
                return 1;
            if (y == null)
                return -1;
            if (x.Presence == null)
                return 1;
            if (y.Presence == null)
                return -1;
    
            return return x.Presence < y.Presence ? -1 : 1;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您是否尝试过您引用的问题中的建议,使用 Linq Cast

      var sorted = uiItems.Cast<Contact>()
                          .OrderBy(c => contact.Presence; );
      

      【讨论】:

      • 当某些项目不是Contacts 时会有不同的行为。
      • 也许 TypeOf 更适合在这里使用。该集合应具有非联系人值。 var sorted = uiItems.TypeOf() .OrderBy(c => contact.Presence; );
      • @voo: OfType 的行为也不完全一样——它从排序的枚举中排除不是Contacts 的对象。
      • 但据我理解的例子,func 必须做完全相同的事情——与 Contact 类型比较并返回过滤后的有序 Contact 集合。如果是这样,TypeOf这里更适合
      【解决方案4】:

      看下面的例子:

      class Item
      {
          public int X;
          public string Y;
      }
      
      var items = new Item[100];
      var ordered = items.OrderBy<Item, string>(i => i.Y);
      

      OrderBy 需要两种类型。前者是可枚举的,后者用于 lambda 表达式。此外,在某些情况下,必须对正在使用的集合元素进行强制转换。如果您确定所有类型都属于特定类型或OfType,则可以在OrderBy 之前使用Cast 方法以省略其他类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-13
        • 2011-09-12
        • 2013-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        相关资源
        最近更新 更多