LINQ命令由委托

时间:2017-07-19 12:09:11

标签: c# linq delegates

我有一组对象要按对象的字段值排序。当前的问题是订单取决于业务逻辑。

public enum Order : byte {
    a = 1,
    b = 2,
    c = 3
}

public class Foo{
    public long A {get;set;}
    public long B {get;set;}
    public long C {get;set;}
}

public class Worker(){
    private Foo[] orderFoos(Foo[] foos, Func<Order, long> sort){
        return foos.OrderByDescending(f => sort(f)).ToArray(foos.Length);
    }

    public void Work(){
        Foo[] foos = getFoos();

        var orderByA = orderFoos(foos, f => f.A);
        var orderByB = orderFoos(foos, f => f.B);
        var orderByC = orderFoos(foos, f => f.C);
    }
}

编译器抛出Argument 1: cannot convert from 'Foo' to 'Order'的错误。有没有解决方法或解决方案?

3 个答案:

答案 0 :(得分:1)

您希望实现的是在不同领域进行排序。如果仅用于此目的,您可能不需要订购枚举,并替换:

private Foo[] orderFoos(Foo[] foos, Func<Order, long> sort){
    return foos.OrderByDescending(f => sort(f)).ToArray(foos.Length);
}

进入

private Foo[] orderFoos(Foo[] foos, Func<Foo, long> sort){
    return foos.OrderByDescending(sort).ToArray(foos.Length);
}

注意:我不确定你是否打算在ToArray方法中添加foos.Length,但据说这超出了问题的范围。

答案 1 :(得分:0)

@hsoesanto给出了一个很好的解决方案,但它没有按照我预期的方式工作 所以我创建了临时解决方法。

private  Func<Foo, long> GetOrderFunction(Order orderType)
{
    switch (orderType)
    {
        case Order.A:
            return (f) => f.A;
        case Order.B:
            return (f) => f.B;
        case Order.C:
            return (f) => f.C;
     }
}

private Foo[] orderFoos(Foo[] foos, Order order)
{
    var orderFunction = GetOrderFunction(order);
    return foos
        .OrderByDescending(f => orderFunction (f))
        .ToArray(foos.Length);
}

答案 2 :(得分:0)

以下代码似乎有效。这是orderFoos方法的一个小改动,有一些示例代码供您测试结果。

using System;
using System.Linq;

public enum Order : byte
{
    a = 1,
    b = 2,
    c = 3
}

public class Foo
{
    public long A { get; set; }
    public long B { get; set; }
    public long C { get; set; }
}

public class Worker
{
    private Foo[] orderFoos(Foo[] foos, Func<Foo, long> sort)
    {
        return foos.OrderByDescending(sort).ToArray();
    }

    public void Work()
    {
        Foo[] foos = { new Foo() { A = 1, B = 2, C = 3 }, new Foo() { A = 10, B = 1, C = 2 }, new Foo() { A = -1, B = 1, C = 10 } };

        var orderByA = orderFoos(foos, f => f.A);
        var orderByB = orderFoos(foos, f => f.B);
        var orderByC = orderFoos(foos, f => f.C);

        Console.WriteLine(orderByA.First().A); // I expect the second to be first here so 10
        Console.WriteLine(orderByB.First().A); // I expect the first to be first here so 1
        Console.WriteLine(orderByC.First().A); // I expect the third to be first here so -1
    }
}

class Program
{
    static void Main(string[] args)
    {
        var worker = new Worker();

        worker.Work();
        Console.ReadLine();
    }
}