c# - 当查询返回匿名类型时,是否可以在 LINQ 中使用 Take?

标签 c# linq anonymous-types

我正在尝试从 LINQ 查询返回的匿名类型列表中获取第 n 个元素,其中 n 是从 0 到 100 的随机数。现在弄乱了一段时间,但我没有得到任何地方。我的代码(更改名称以保护 IP):

var query = from Table1 t1 in theContext.Table1 
   join Table2 t2 in theContext.Table2
    on ... 
    where ... 
   select new 
   {
       partNum = t1.part_number, 
       partSource = t2.part_source
   }

int num = new Random().Next(0, 100); 

// here's where the code I've tried fails 

我能以某种方式做一个Take<T>(100).ToList<T>()[num]吗?使用partNum 和partSource 获得单个匿名类型?我最终通过显式定义类型解决了这个问题,但似乎我在这里错过了一个更优雅的解决方案。我只想返回 Dictionary<string, string>给调用者,所以我宁愿不必在此方法之外定义类型。

更新:ElementAt 不适用于此。我尝试添加:

// get a random part from the parts list
int num = new Random().Next(0, query.Count() - 1 );
var nthElement = query.ElementAt(num);

我遇到了一个异常(exception):The query operator 'ElementAt' is not supported.

最佳答案

您应该能够使用:

var item = query.Take(100).ToList()[num];

当然,这样做会更有效率:

var item = query.Skip(num).First();

关于c# - 当查询返回匿名类型时,是否可以在 LINQ 中使用 Take?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831837/

相关文章:

c# - 将对公共(public) setter 的访问限制为特定对象 (C#)

asp.net-mvc - LINQ 父子关系

c# - 在 C# 中返回匿名类型

c# - 阻止访问私有(private)成员变量?强制使用公共(public)属性(property)?

c# - for 循环优化 - 需要还是不需要?

c# - 如何在 lambda 表达式中使用带有 out 参数的方法

c# - 如何将键值对列表转换为动态对象

vb.net - LINQ 用空字符串替换 DBNull

c# - LINQ OrderBy 异常

dynamic - 匿名类型列表和动态...混淆