I always want to be a smart developer that is why i always be in search in one line optimized code which could solve my problem soon in smart way. Today i was trying to filter list with match an item to get Boolean value. Instead of using loop and going with FirstOrDefault of lambda i tried Any keyword and its worked for me.
Best Code samples :
Best Code samples :
using System.Linq;
bool has = list.Any(o => o.name == "Raj");
var hasRaj = (from customer in list where customer.FirstName == "Raj" select customer).Any();
Employee emp = AllEmp.FirstOrDefault(o => o.name == "Raj");
if (emp != null)
{
// Use emp
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List list = new List();
list.Add(7);
list.Add(11);
list.Add(13);
// See if any elements with values greater than 10 exist
bool exists = list.Exists(element => element > 10);
Console.WriteLine(exists);
// Check for numbers less than 7
exists = list.Exists(element => element < 7);
Console.WriteLine(exists);
}
}
Output
True
False