Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Yield Return Statement in C# | Yield keyword in C#

  In this article, we will learn about the Yield keyword in C#

The yield keyword informs the compiler that the method in which it is used, is an iterator block over collection. An iterator block returns the IEnumerable as the output And the yield keyword is used to return values for the IEnumerable.

Yield Keyword in C#

We cant use the Yield keyword alone in C#, we have to use it either with a return or break statement.

yield return - specifies the next item value of the iterator

yield return <expression>;
Docker

 The yield return statement returns one item value at a time. The return type of the yield keyword is either the IEnumerator or IEnumerable.

yield-break - specifies the end of the iteration

yield break;
Docker

Important about using yield are:

  • lazy evaluation
  • deferred execution

The yield return and yield break statements are not allowed to use in the anonymous methods and the methods which contain unsafe blocks.

Keypoint to remember while using Yield

  • The return type of the yield should be the IEnumerator or IEnumerable object of values.
  • Should not use ref or out keyword with the parameters of method, property, or operator,.
  • In c#, the yield return statement can be used in the try block of the try-finally statement.
  • The yield break statement can be used in the try or catch block but not in the final block.
1static void Main(string[] args) {
2 foreach(int i in Add()) {
3 Console.Write("{0} ", i);
4 }
5 Console.ReadLine();
6}
7public static IEnumerable < int > Add() {
8 var val = new List < int > ();
9 for (int i = 1; i < 10; i++) {
10 val.Add(i + 1);
11 }
12 return val;
13}
C#

Output


In the above example, we return the entire list at a time, but what if we want to return an item with iteration, in that case, we use Yield return.

1static void Main(string[] args) {
2 foreach(int i in Add()) {
3 Console.Write("{0} ", i);
4 }
5 Console.ReadLine();
6}
7public static IEnumerable < int > Add() {
8 var val = 1;
9 for (int i = 0; i < 10; i++) {
10 yield
11 return val + i;
12 }
13}
C#

Output


Below is the logic difference between Return and Yield return in C#




 

Yield Break in C#

we use the yield break statement to break the iteration or loop and exit from the iterator block on particular conditions. The yield break statement is just like the normal break statement in C#,.

The break statement is used to exit the loop just before its normal termination.

On the other side, the yield break statement is used in the iterator block to stop the iteration and indicate that there are no more values existing in the sequence.

Below is the program code,

1static void Main(string[] args) {
2 foreach(int i in PrintNumberLessThanFive()) {
3 Console.Write("{0} ", i);
4 }
5Console.ReadLine();
6}
7public static IEnumerable < int > PrintNumberLessThanFive() {
8 for (int num = 0; num < 10; num++) {
9 if (num < 5) {
10 yield
11 return num;
12 } else {
13 yield
14 break;
15 }
16 }
17}
C#


 

Output



-----------------------------------------------------------------------------------------------------

Integrate OpenAI with .NET Core and Angular15 | ChatGPT Completions In .NET Core Web API & Angular15

Hello everyone, Here we are going to discuss, how to integrate OpenAI with .Net Core and Angular 15.

ChatGPT Completions In .NET Core Web API & Angular15

ChatGPT (Generative Pre-trained Transformer) is the chatbot developed by OpenAI on November 30, 2022.

Previously we discussed OpenAI and we have seen how to create a ChatGTP application using OpenAI, 

For more please follow the below link 👇

Step 1 - Create an OpenAI account

First, we need to create an OpenAI account; you can follow the below link to how to create an OpenAI account.

Step 2 - Get the OpenAI API key

Login to your OpenAI account and click on profile (personal, right-hand side) and click on view API

ChatGPT Completions In .NET Core Web API & Angular15

Once you click on View API Keys, you will ‘Create a new secret key, once you click on it an API key will generate in the Popup window, and you can copy it for using it in the application.

ChatGPT Completions In .NET Core Web API & Angular15

 

ChatGPT Completions In .NET Core Web API & Angular15

Now open visual studio 2022 and create an Asp.net Core web API project like below

ChatGPT Completions In .NET Core Web API & Angular15

ChatGPT Completions In .NET Core Web API & Angular15

Give additional information as per your requirement.

ChatGPT Completions In .NET Core Web API & Angular15

Once the project is created, now go to the NuGet package manager and add the OpenAI package like below

ChatGPT Completions In .NET Core Web API & Angular15

Now right-click on the Controller folder and add a new controller Called OpenAI and write the below code in it

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenAI_API.Completions;
using OpenAI_API;
namespace OpenAIApp.Controllers {
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OpenAI: ControllerBase {
        [HttpGet]
        public async Task < IActionResult > GetData(string input) {
            string apiKey = "Your API Key";
            string response = "";
            OpenAIAPI openai = new OpenAIAPI(apiKey);
            CompletionRequest completion = new CompletionRequest();
            completion.Prompt = input;
            completion.Model = "text-davinci-003";
            completion.MaxTokens = 4000;
            var output = await openai.Completions.CreateCompletionAsync(completion);
            if (output != null) {
                foreach(var item in output.Completions) {
                    response = item.Text;
                }
                return Ok(response);
            } else {
                return BadRequest("Not found");
            }
        }
    }
}
C#

Now click on the program.cs class and add the cors origin like below,

builder.Services.AddCors(options => {
    options.AddPolicy(name: "AllowOrigin", policy => {
        policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});
app.UseCors("AllowOrigin");
C#

ChatGPT Completions In .NET Core Web API & Angular15

When you will run this application, we will see our API in swagger and our API is ready to use in angular

ChatGPT Completions In .NET Core Web API & Angular15

Now we need to create the Angular 15 application, you can follow the below link for the same

once the angular 15 application is created, now open the app.component.ts file and add the below code

import { Component } from '@angular/core';
import { OpenAIService } from './open-ai.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    searchTxtVal: string = '';
    showOutput: boolean = false;
    output: string = '';
    isLoading: boolean = false;
    constructor(private service: OpenAIService) {}
    getResult() {
        this.isLoading = true;
        this.output = "";
        this.service.getData(this.searchTxtVal).subscribe(data => {
            this.output = data as string;
            this.showOutput = true;
            this.isLoading = false;
        })
    }
}
JavaScript

Add the below code in app.component.html file

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div class="text-center">
  <div class="panel-default">
    <div class="panel-body">ChatGPT Completions In the ASP.NET Core Web API</div>
    <div class="panel-body">
      <div class="col-sm-8">
        <input type="text" [(ngModel)]="searchTxtVal" class="form-control" autocomplete="off" placeholder="Enter your question" />
      </div>
      <div class="col-sm-2" style="margin-left: -60px;">
        <button (click)="getResult()">Get Result</button>
      </div>
      <div class="col-sm-12 mt-5" *ngIf="showOutput">
        {{output}}
      </div>
      <div class="col-sm-12 mt-5" *ngIf="isLoading">
        <p style="color: red;">Loading...</p>
      </div>
    </div>
  </div>
</div>
JavaScript

Now create a service file with the below command, here service name is ‘OpenAI’

Ng g s openAI

And write the below code in the openAI.service.ts file

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import{ Observable} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class OpenAIService {
    constructor(private http: HttpClient) {}
    getData(input: string): Observable < any > {
        return this.http.get('https://localhost:7285/api/OpenAI/GetData?input=' + input, {
            responseType: 'text'
        });
    }
}
JavaScript

In the above the Url path is ‘'https://localhost:7285’, you need to replace the port, which you are looking at locally, once you run your .Net Core application.

Now add this service reference in the app.model.ts file in the provider array and apart from it we need to add the FormsModule and HttpClientModule like below

ChatGPT Completions In .NET Core Web API & Angular15

Now when you will run your angular 15 application, you will see UI like below

ChatGPT Completions In .NET Core Web API & Angular15

Here, now you can write your query and click on the getResult button, you will see the output below

ChatGPT Completions In .NET Core Web API & Angular15

The output will be like below

ChatGPT Completions In .NET Core Web API & Angular15

This is the way we can integrate the OpenAI with our angular application.

Below is the video, on how we can integrate OpenAI with our angular application practically,





----------------------------------------------------------------

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now