First

In this chapter you will learn:

  1. How to use First operator
  2. Use First with expression
  3. First with string method
  4. 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:

  1. C# Linq FirstOrDefault operator
  2. FirstOrDefault with filter delegate
  3. Get the first or the default
  4. FirstOrDefault vs First
  5. FirstOrDefault and string operation
  6. FirstOrDefault with a Not Found Element
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip