.Any() - returns boolean.
The LINQ Any() method checks if at least one element in a collection satisfies a condition—or if the collection has any elements at all.
//----------------------------------------------
.All()
true if all elements match the condition. false if any one element fails the condition.
example
int[] numbers = { 2, 4, 6, 8 };
bool allEven = numbers.All(n => n % 2 == 0); // returns true
//------------------------------
use Count() without parameters to get the total number of elements, or pass a predicate (like n => n > 25) to count only those that match a condition.
example:
int[] numbers = { 10, 20, 30, 40, 50 }; // Count all elements int totalCount = numbers.Count(); // Count elements greater than 25 int countGreaterThan25 = numbers.Count(n => n > 25);
//--------------------------
The Contains() method checks whether a sequence contains a specified element and returns a boolean result.
example:
string[] fruits = { "apple", "banana", "mango", "orange" };
// Check if "mango" exists in the array
bool hasMango = fruits.Contains("mango");
//-------------------------
string[] names = { "Zara", "Adam", "John", "Bella" };
// Sort names in ascending order
var sortedNames = names.OrderBy(name => name);
OrderByDescending() if you want to sort in reverse order:
var descendingNames = names.OrderByDescending(name => name);
//---------------------------
Min
//---------------------------
Max
//---------------------------
Average
int[] numbers = { 10, 20, 30, 40, 50 };
double avg = numbers.Average();
//----
double averageMarks = students.Average(s => s.Marks);
//---------------------------
Sum
int[] numbers = { 10, 20, 30, 40, 50 };
// Using LINQ Sum method
int total = numbers.Sum();
//--- products.Sum(p=>p.Price);
//---------------------------
ElementAt(index) for IEnumerable<int>
to avoid exception use ElementAtOrDefault(index)
//---------------------------
FirstOrDefault()
LastOrDefault()
//----------------------------
Single()
//----
SingleOrDefault()
This method returns the only element that matches a condition, or the default value (null for reference types) if no such element exists. It throws an exception if more than one match is found.
var users = new List { "Alice", "Bob", "Charlie" }; // This will return "Bob" string result = users.SingleOrDefault(u => u == "Bob");
//---------------------------
Where
//---------------------------
Take(int), TakeLast(int)
//--
TakeWhile()
int[] numbers = { 10, 20, 30, 60, 40, 50 };
var result = numbers.TakeWhile(n => n < 50);
//-----------------------------
Skip(int), SkipLast(int), SkipWhile(int)
numbers.Skip(2).Take(2)
numbers.SkipWhile(number => number < 20)
//------------------------------
OfType<T>
ArrayList items = new ArrayList();
items.Add("hello"); items.Add(42); items.Add("world"); items.Add(3.14);
// Filter only strings
var strings = items.OfType<string>();
//----------------------------------------------------
Distinct()
List<int> numbers = new List<int>() { 1, 2, 3, 2, 4, 3, 5 };
var distinctNumbers = numbers.Distinct();
O/P: { 1,2,3,4,5 }
SyntaxEditor Code Snippet
public static IEnumerable<T> GetCollectionWithMostDuplicates<T>(IEnumerable<IEnumerable<T>> collections)
{
return collections.OrderBy
(collection => collection.Count() - collection.Distinct().Count())
.ThenByDescending(collection=>collection.Count())
.LastOrDefault();
}
//------------------------------------------
Append() & Prepend()
//--------------------------------------
Concat() & Union()
example
numbers1.Concat(numbers2)
num1.Union(num2) -- remove duplicates
var unionofpets = pets1.Union(pets, PetEqualityByIdComparer);// - union by two reference collection
//--------------------------------------------------------------------
.ToArray()
.ToList()
.ToHashSet()
//---
.ToDictionary(p=>p.id,p=>p.Name)
//---
.ToLookup(p=>p.PType, p.PName)
//---
.AsEnumerable()
//---
= numbers.Cast<long>();
example:
IEnumerable<PType> allptype = Enum.GetValues(typeof(PType)).Cast<PType>();
//------------------------------------------------------------------------------
Select()
One-to-One Projection
var words = new[] { "apple", "banana" }; var result = words.Select(word => word.ToUpper());
Result: { "APPLE", "BANANA" }
//---------------------------------------------------------------------------
SelectMany()
One-to-Many Flattening
var words = new[] { "apple", "banana" };
var result = words.SelectMany(word => word.ToCharArray());
Result:
{ 'a', 'p', 'p', 'l', 'e', 'b', 'a', 'n', 'a', 'n', 'a' }
Each word becomes a sequence of characters, and SelectMany() flattens them into one big sequence.
//-------------------------------------------------------------------------------------------
Generating New Collections
Enumerable.Empty<int>();
Enumerable.Repeat(100,10)
var foxes = Enumerable.Repeat("fox",3).Select((word,index)=>$"{index+1} {word}");
var tenToThirty = Enumerable.Range(10,21);
var letters = Enumerable.Range('A',10).Select(number=>(char)number);
//-------------------------------------------------------------------------------------------
GroupBy
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Branch { get; set; }
}
var students = new List { new Student { ID = 1, Name = "Alice", Branch = "CSE" }, new Student { ID = 2, Name = "Bob", Branch = "ECE" }, new Student { ID = 3, Name = "Charlie", Branch = "CSE" }, new Student { ID = 4, Name = "David", Branch = "EEE" }, new Student { ID = 5, Name = "Eva", Branch = "ECE" } };
// Grouping by Branch
var groupedByBranch = students.GroupBy(s => s.Branch);
foreach (var group in groupedByBranch)
{
Console.WriteLine($"Branch: {group.Key}");
foreach (var student in group)
{
Console.WriteLine($" {student.Name} (ID: {student.ID})");
}
}
//-------------------------------------------------------------------
Intersect & Except
List list1 = new List { 1, 2, 3, 4, 5, 6 };
List list2 = new List { 1, 3, 5, 8, 9, 10 };
var common = list1.Intersect(list2);
Console.WriteLine("Common elements:");
foreach (var item in common) { Console.WriteLine(item); }
//-----
List list1 = new List { 1, 2, 3, 4, 5, 6 };
List list2 = new List { 1, 3, 5, 8, 9, 10 };
var onlyInList1 = list1.Except(list2);
Console.WriteLine("Elements only in list1:");
foreach (var item in onlyInList1) { Console.WriteLine(item); }
//-------------------------------------------------------------------------------------
Joins - Go to Linq query
GroupJoin - Go to Linq query
LeftJoin - Go to Linq query
//--------------------------------------------------------------------------
Aggregate
var numbers = new[ ] {10,1,4,17,122}
var sumOfNumbers = numbers.Aggregate((sum, nextNumber) => sum + nextNumber);
//--------------------------------------------------------------------------
Zip
var numbers = new[ ] {1, 2, 3, 4, 5}
var words = new words[ ] { "The", "quick", "brown", "fox", "jumps" };
var numbersZippedWithWords = numbers.Zip(
words,
(number, word) => $"{number}, {word}");
var numberWordDictionary = number.Zip(words).ToDictionary(
tuple => tuple.First,
tuple => tuple.Second);
//--------------------------------------------------------------------------
(.Net 6)
MinBy(), MaxBy(), DistinctBy, Chunk()
var heaviestpet = pets.MaxBy(pet=>pet.Weight);
var petWithShortestName = pets.MinBy(pet.pet.Name.Length);
//-----------------------------------------------------------------------------
.TryGetNonEnumeratedCount(out var count)
//---------------------------------------------------------------------------------
(.Net 9)
CountBy(), AggregateBy()
//-------------------------------------------------------------------------------