Error: Sequence contains no matching element in C# Asp.Net

Dung Do Tien May 17 2022 507

I have created a service in .Net 6 that helps get a list of data and transfer it to the MySQL database. I wrote a function help insert data like this:

 public async Task<int> MultipleInserBooks(List<BooksInfoEntities> books)
{
    try
    {
        if (books == null || !books.Any()) return 0;
        List<BooksInfoEntities> newBooks = new List<BooksInfoEntities>();
        
        // check duplicate books
        foreach (var book in books)
        {
            if (!string.IsNullOrEmpty(book.BookName))
            {
                var bookObj = newBooks.First(x => x.BookName.Trim().Equals(book.BookName));
                if (bookObj == null)
                {
                    newBooks.Add(book);
                }
            }
        }
        
        // Insert books and return
        return updateBooks(newBooks);
    }
}

But when calling this method I got an exception threw System.InvalidOperationException: Sequence contains no matching element.

 System.InvalidOperationException: Sequence contains no matching element
   at BooksIndexer.Dal.BooksService.BooksServiceDal.<MultipleInserTokenSpam>d__3.MoveNext() in C:\Project\Books\Books.IO\BooksIndexer\BooksIndexer\BooksIndexer\BooksIndexer.Dal\BooksService\BooksServiceDal.cs:line 196
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at BooksIndexer.Bsl.BooksService.BooksServiceBsl.<Run>d__2.MoveNext() in C:\Project\Books\Books.IO\BooksIndexer\BooksIndexer\BooksIndexer\BooksIndexer.Bsl\BooksService\BooksServiceBsl.cs:line 44Round 2 is starting....
   

What is that mean?

I used VS2022 and .Net 6.0, Window 11.

Thanks in advance.

Have 1 answer(s) found.
  • Z

    Zvonimir Markov May 17 2022

    I got same the error as you. See this line of code below:

     var bookObj = newBooks.First(x => x.BookName.Trim().Equals(book.BookName));

    You got this issue because you are using First() LinQ function.

    Solution: Change First() to FirstOrDefault() function. And your issue will be solved.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close