c# - Mongodb 在使用 Take(1) 时返回多个结果

标签 c# linq mongodb

我只想使用 C# LINQ 获取一行:

collection.AsQueryable().Take(1).OrderByDescending(x => x.Id).Single();

我收到以下错误:

序列包含多个元素

这不是 Take(1) 的用途吗?
更新1 这是只获取没有单个/第一个的结果...

enter image description here

最佳答案

在我的情况下它有效

        int[] grades = { 1 , 2, 3 };
        Console.WriteLine(grades.Take(1).Single());

        //the result is 
        // 1

更广泛的例子

        var a = new List<int>{10, 20, 30};
        var b = new List<int>{100, 200, 300};
        var grades = new List<List<int>>{a, b};
        Console.WriteLine(grades.Take(1).Single());

产生的结果

List<Int32> (3 items)
10 
20 
30 

LINQ 语句的顺序很重要

检查这两个例子

        int[] grades = { 1, 2, 3, 4, 5 };

        IEnumerable<int> topThreeGrades =
            grades.Take(3).OrderByDescending(grade => grade);

        Console.WriteLine("The top three grades are:");
        foreach (int grade in topThreeGrades)
        {
            Console.WriteLine(grade);
        }

产生

The top three grades are:
3
2
1

但是

        int[] grades = { 1, 2, 3, 4, 5 };

        IEnumerable<int> topThreeGrades =
            grades.OrderByDescending(grade => grade).Take(3);

        Console.WriteLine("The top three grades are:");
        foreach (int grade in topThreeGrades)
        {
            Console.WriteLine(grade);
        }

会产生

The top three grades are:
5
4
3

关于c# - Mongodb 在使用 Take(1) 时返回多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27393845/

相关文章:

c# - 如何加入收到的多部分短信(GSM 调制解调器)(C#)

c# - 从通用列表中过滤记录<string>

javascript - jQuery 像 Linq 一样?

c# - 是否组合了不同的 IQueryable 对象?

MongoDB 检查数组中是否存在

javascript - 将变量从 shell 脚本传递到 js 脚本

c# - 为什么在 web api 方法中返回接口(interface)时,我得到的是具有接口(interface)值的继承类的值?

c# - 混合模式 .NET 程序集是否具有更好的性能?

c# - 使用 Linq 将字符串拆分为 List<string>

node.js - Mongoose 更新不更新