簡體   English   中英

使用Take(1)時,Mongodb返回多個結果

[英]Mongodb returns more than one result when using Take(1)

我想用C#LINQ只獲取一行:

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

我收到以下錯誤:

Sequence contains more than one element

這不是Take(1)的用途嗎?
UPDATE1這是僅在沒有單個/第一個的情況下獲取的結果...

在此輸入圖像描述

在我的情況下它是有效的

        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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM