c# - 扩展选择要在 Linq 中使用的扩展

标签 c# .net linq linq-to-objects

是否可以选择在 Linq 中应用哪个函数?
我现在拥有的示例:

List<int> list = new List<int>();
bool bDescend = false;
var listOrdered = bDescend ? list.OrderByDescending(it => it) : 
                             list.OrderBy(it => it);

您看到我根据 bDescend 值选择应用哪个函数 - 所以实际上有两个 Linq 查询,而不是一个。
是否可以通过将条件放在一个查询中来避免它? 也许像

list.ChooseFunction(bDescend ? OrderBy : OrderByDescending)...

真正的代码更合规,如果这种技巧可行,它会使代码更具可读性。
看起来像是一种元编程。

最佳答案

您可以创建自己的扩展方法:

enum Ordering
{
    Ascending,
    Descending,
}

// trivial to convert to use booleans instead
// of an enum if that's truly what you need
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source, Ordering ordering, Func<TSource, TKey> keySelector) 
{
    if (ordering == Ordering.Ascending)
    {
        return source.OrderBy(keySelector);
    }
    else
    {
        return source.OrderByDescending(keySelector);
    }
}

然后像这样调用它

var order = Ordering.Descending;
....
MyList.OrderBy(order, it => it);

除此之外,可以制作一个 ChooseFunction 类型的东西,但它必须看起来像 ChooseFunction(bdescend ? "OrderBy": "OrderByDescending")我什至不想深入了解那些引用函数名称的神奇字符串有多难看。您还必须对 ChooseFunction 扩展进行硬编码,或者依赖反射,这对于您尝试做的简单事情来说代价高得离谱

关于c# - 扩展选择要在 Linq 中使用的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169951/

相关文章:

linq - Entity Framework 似乎不必要地两次加入同一个表

c# - LINQ 如何删除集合末尾的空元素

c# - 如何从 WPF 中的原始帧渲染视频?

c# - 使用 itextsharp(C#/asp.net) 在 pdf 中设置文本或图像的位置

c# - 对两个数组(值,键)进行排序,然后对键进行排序

c# - DateTimeOffset.UtcNow.DateTime 是否等同于 DateTime.UtcNow?

.net - 将 ClickOnce wpf 应用程序部署到 Windows Azure Blob 存储

c# - 在 C# 中获取屏幕像素颜色的最快方法

.net - 如何使用其他名称创建新的 System.String 类型?

c# - morelinq 通过多个属性来区分