First
In this chapter you will learn:
- How to use First operator
- Use First with expression
- First with string method
- Retrieving all strings in an array whose length matches that of the shortest string
Get to know First operator
using System;//from java2s. c om
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
int first = numbers.First();
int firstEven = numbers.First(n => n % 2 == 0);
Console.WriteLine(first);
Console.WriteLine(firstEven);
}
}
The output:
Use First with expression
using System;/* j ava 2 s . c om*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var query = numbers.First(n => n % 2 == 0);
Console.Write(query);
}
}
First with string method
using System;/*from j a va2s.c o m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "java2s.com", "a", "H", "over", "Jack"};
string name = presidents.First(p => p.StartsWith("j"));
Console.WriteLine(name);
}
}
First after select
using System;// ja v a 2 s . c om
using System.Collections.Generic;
using System.Linq;
public class MainClass {
public static void Main() {
string[] names = { "Java", "java2s.com", "java2", "java2s" };
IEnumerable<string> outerQuery = names
.Where(n => n.Length == names.OrderBy(n2 => n2.Length)
.Select(n2 => n2.Length).First());
}
}
Next chapter...
What you will learn in the next chapter:
- C# Linq FirstOrDefault operator
- FirstOrDefault with filter delegate
- Get the first or the default
- FirstOrDefault vs First
- FirstOrDefault and string operation
- FirstOrDefault with a Not Found Element
Home » C# Tutorial » Linq Operators