C# Program to return the only element that satisfies a condition

CsharpProgrammingServer Side Programming

The Single() method returns the only element that satisfies a condition. If more than one such element is visible, then an error is thrown.

The following is our string array.

string[] str = { "jack", "tom", "henry", "time"};

Now, use the Single() method to get each element. Then, we have used Lambda Expression to calculate an element whose length is greater than four.

str.AsQueryable().Single(name => name.Length > 4);

Example

 Live Demo

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      string[] str = { "jack", "tom", "henry", "time"};
      // finding string whose length is greater than 4
      string res = str.AsQueryable().Single(name => name.Length > 4);
      Console.WriteLine(res);
   }
}

Output

henry
raja
Updated on 23-Jun-2020 08:26:45

Advertisements