c# - 自定义 Linq 扩展语法

标签 c# linq generics extension-methods

我编写了一个函数,可以从列表中获取给定数量的随机记录。目前我可以做类似的事情:

IEnumerable<City> cities = db.Cites.GetRandom(5);

(其中 db 是我连接到 SQL Server 数据库的 DataContext)

目前,我在每个需要随机记录的实体中都有这样的函数:

public partial class City
{

    public static IEnumerable<City> GetRandom(int count)
    {
        Random random = new Random();
        IEnumerable<City> cities = DB.Context.Cities.OrderBy( c => random.Next() ).Take(count);

        return cities;
    }

}

它工作正常,但我希望它是通用的,这样它就可以用于任何表格,甚至任何项目列表。我尝试了一种扩展方法,例如:

    public static IEnumerable<T> GetRandom<T>( this Table<T> table, int count)
    {
        Random random = new Random();
        IEnumerable<T> records = table.OrderBy(r => random.Next()).Take(count);

        return records;
    }

但我得到:

  Error 1   The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table' 

突出显示 GetRandom<T> .

我不明白这里的问题是什么。有人可以清除正确的语法吗?

最佳答案

我喜欢随机排序函数的想法,它可以像这样应用于任何 IEnumerable:

public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
    Random rnd = new Random();
    return source.OrderBy(t => rnd.Next());
}

...

IEnumerable<City> cities = db.Cites.Randomize().Take(5);

关于c# - 自定义 Linq 扩展语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/351915/

相关文章:

c# - 如何从 foreach 中访问 Viewbag 中特定索引处的对象的属性?

c# - vNext EF7 代码首次迁移。无法加载一种或多种请求的类型

C# linq 选择列表中的对象查看另一个对象列表

Java,通用类型的通用接口(interface)——一个糟糕的设计?

C# Regex Replace 附加换行符

c# - 在 MVC View 中格式化数字

c# - 从另一个列表 LINQ 获取仅包含第一个和最后一个字符的字符串列表

c# - Nullable int 在 LINQ (C#) 中无法正常工作

delphi - D2009 中的泛型可以在大型项目中使用吗?

ios - 我怎样才能在 Swift 5.1 (Xcode 11 Playground) 中为可选项实现泛型和非泛型函数签名的重载?