首页 >后端开发 >C++ >如何使用字符串表达式动态订购iEnumerable且可音录?

如何使用字符串表达式动态订购iEnumerable且可音录?

Susan Sarandon
Susan Sarandon原创
2025-02-02 22:31:10842浏览

How Can I Dynamically Order IEnumerable and IQueryable Using String Expressions?

使用字符串表达式动态排序 IEnumerable / IQueryable

原始问题:

在搜索动态 LINQ 示例时,发现了一种方法可以使用类似 SQL 的字符串(例如,“OrderBy("Name, Age DESC")”)对 IQueryable 实例进行排序。有没有办法将此功能扩展到 IEnumerable

答案:

为了在不使用 Dynamic LINQ 库的情况下实现这一点,以下代码片段提供了核心表达式逻辑:

<code class="language-C#">public static IOrderedQueryable<T> OrderBy<T>(
    this IQueryable<T> source,
    string property)
{
    return ApplyOrder<T>(source, property, "OrderBy");
}

// ...省略其余代码以简洁起见...</code>

此代码允许通过将 IEnumerable 包装在 AsQueryable() 中来对其进行排序。

动态 LINQ 集成的扩展:

将此功能扩展到动态 LINQ:

<code class="language-C#">using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Runtime.CompilerServices;

// ...省略其余代码以简洁起见...

public static IOrderedEnumerable<dynamic> OrderBy(
    this IEnumerable<dynamic> source,
    string property)
{
    return Enumerable.OrderBy<dynamic>(
        source,
        AccessorCache.GetAccessor(property),
        Comparer<object>.Default);
}

// ...省略其余代码以简洁起见...</code>

此代码在 LINQ to Objects 中提供了动态排序功能。

以上是如何使用字符串表达式动态订购iEnumerable且可音录?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn