jco*_*lum 3 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
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式做一个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);
Run Code Online (Sandbox Code Playgroud)
我有一个例外: The query operator 'ElementAt' is not supported.
你应该可以使用:
var item = query.Take(100).ToList()[num];
Run Code Online (Sandbox Code Playgroud)
当然,这样做会更有效率:
var item = query.Skip(num).First();
Run Code Online (Sandbox Code Playgroud)