How to use FirstOrDefault() to get first value or default value from a collection in C#

3 Answers

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<string>() { "c#", "c", "c++", "java" };

            Console.WriteLine(list.FirstOrDefault());
        }
    }
}


/*
run:
     
c#

*/

 



answered Feb 22, 2017 by avibootz
0 votes
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<string>() { "c#", "c", "c++", "java" };

            var query = from element in list
                        where element.Length > 5
                        select element;
            Console.WriteLine(query.FirstOrDefault() == null);
        }
    }
}


/*
run:
     
True

*/

 



answered Feb 22, 2017 by avibootz
0 votes
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<string>() { "c#", "c", "c++", "java" };

            var query = from element in list
                        where element.Length > 3
                        select element;
            Console.WriteLine(query.FirstOrDefault());
        }
    }
}


/*
run:
     
java

*/

 



answered Feb 22, 2017 by avibootz

Related questions

...