LINQ - Differences

 1. Queryable vs Enumerable in LINQ

Queryable (found in System.Linq.Queryable) is used for LINQ queries that work with IQueryable collections. It is often used with databases or any collection that supports deferred execution (e.g., Entity Framework queries). The queries are translated into the provider's query language (like SQL).

Enumerable (found in System.Linq.Enumerable) is used for LINQ queries on IEnumerable collections (like arrays, lists, or other in-memory collections). It is intended for querying collections that reside in memory and supports immediate execution.



2. Distinct vs GroupBy in LINQ

Distinct: This method is used to return distinct (unique) elements from a collection, removing duplicates based on the equality of the elements.

Example:

var distinctNumbers = numbers.Distinct();


GroupBy: This method is used to group elements in a collection based on a key. It does not eliminate duplicates but groups them together.

Example:

var groupedNumbers = numbers.GroupBy(x => x);



3. Except vs Where in LINQ

Except: This method is used to subtract one collection from another, returning elements in the first collection that do not appear in the second collection.

Example:

var difference = collection1.Except(collection2);


Where: This method filters elements based on a given predicate and returns a new collection with only those elements that satisfy the condition.

Example:

var filteredNumbers = numbers.Where(x => x > 5);



4. Union vs Where in LINQ

Union: Combines two collections and removes duplicates, returning a distinct set of elements from both collections.

Example:

var combined = collection1.Union(collection2);


Where: Filters elements based on a given condition. It doesn’t combine collections but filters them based on a predicate.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



5. Contains vs Where in LINQ

Contains: Checks if a specific element exists in a collection, returning a boolean (true or false).

Example:

bool exists = numbers.Contains(5);


Where: Filters elements based on a condition and returns a new collection with the elements that meet the predicate.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



6. SkipWhile vs Where in LINQ

SkipWhile: Skips elements from the beginning of the collection as long as a condition is true, and then returns the remaining elements.

Example:

var remainingNumbers = numbers.SkipWhile(x => x < 5);


Where: Filters elements based on a condition and returns a new collection.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



7. ToList vs Array in LINQ

ToList: Converts the results of a LINQ query into a List<T>, which is a dynamic collection.

Example:

var list = numbers.Where(x => x > 5).ToList();


Array: Converts the LINQ result into an array. The length of the array is fixed, and it's a statically-typed collection.

Example:

var array = numbers.Where(x => x > 5).ToArray();



8. Cast vs OfType in LINQ

Cast: Attempts to cast each element of a collection to a specific type. It throws an exception if an element cannot be cast.

Example:

var casted = numbers.Cast<int>();


OfType: Filters elements of a collection to only include those that can be cast to a specified type.

Example:

var ofType = numbers.OfType<int>();



9. OrderBy vs ThenBy in LINQ

OrderBy: Orders a collection based on a specified key, in ascending order by default.

Example:

var ordered = numbers.OrderBy(x => x);


ThenBy: Provides a secondary sorting criterion when sorting a collection, used after OrderBy or another ThenBy.

Example:

var ordered = numbers.OrderBy(x => x).ThenBy(x => x.Length);



10. OrderByDescending vs ThenByDescending in LINQ

OrderByDescending: Orders the collection in descending order based on a key.

Example:

var orderedDescending = numbers.OrderByDescending(x => x);


ThenByDescending: Provides a secondary sorting criterion for descending order after an OrderByDescending.

Example:

var orderedDescending = numbers.OrderByDescending(x => x).ThenByDescending(x => x.Length);



11. Aggregate vs Reduce in LINQ

Aggregate: Performs a cumulative operation on the elements of a collection, using an accumulator. It’s commonly used for aggregation or transformation.

Example:

var sum = numbers.Aggregate((a, b) => a + b);


Reduce: Not available in LINQ directly, but the concept of reducing a collection is similar to Aggregate.



12. Select vs Where in LINQ

Select: Projects each element of a collection into a new form (transformation).

Example:

var squaredNumbers = numbers.Select(x => x * x);


Where: Filters elements of a collection based on a condition.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



13. SelectMany vs Where in LINQ

SelectMany: Flattens a collection of collections (or sequences) into a single collection. It’s often used when the result is a collection of collections (e.g., lists of lists).

Example:

var flattened = numbers.SelectMany(x => x);


Where: Filters elements based on a condition.

Example:

var filtered = numbers.Where(x => x > 5);



14. Any vs Where in LINQ

Any: Returns true if at least one element in a collection satisfies a condition.

Example:

bool anyGreaterThanFive = numbers.Any(x => x > 5);


Where: Filters elements based on a condition and returns a new collection.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



15. All vs Where in LINQ

All: Checks if all elements in the collection satisfy a condition.

Example:

bool allGreaterThanFive = numbers.All(x => x > 5);


Where: Filters elements based on a condition and returns a new collection.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



16. First vs Where in LINQ

First: Returns the first element in the collection that satisfies a condition (throws an exception if not found).

Example:

var firstGreaterThanFive = numbers.First(x => x > 5);


Where: Filters elements based on a condition and returns a collection of matching elements.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



17. Single vs Where in LINQ

Single: Returns the single element that satisfies a condition (throws an exception if there is more than one or no matching elements).

Example:

var singleGreaterThanFive = numbers.Single(x => x > 5);


Where: Filters elements based on a condition and returns a collection of matching elements.

Example:

var greaterThanFive = numbers.Where(x => x > 5);



18. Zip vs Join in LINQ

Zip: Combines two sequences by applying a function to corresponding elements, creating a new sequence of results.

Example:

var zipped = numbers.Zip(letters, (n, l) => new { n, l });


Join: Joins two collections based on a matching key.

Example:

var joined = numbers.Join(letters, n => n, l => l, (n, l) => new { n, l });



19. TakeWhile vs SkipWhile in LINQ

TakeWhile: Takes elements from the beginning of the collection as long as a condition is true.

Example:

var taken = numbers.TakeWhile(x => x < 5);


SkipWhile: Skips elements from the beginning of the collection as long as a condition is true, then returns the rest.

Example:

var skipped = numbers.SkipWhile(x => x < 5);



20. ElementAt vs ElementAtOrDefault in LINQ

ElementAt: Retrieves the element at a specified index, throwing an exception if the index is out of range.

Example:

var element = numbers.ElementAt(2);


ElementAtOrDefault: Retrieves the element at a specified index, returning null or a default value if the index is out of range.

Example:

var element = numbers.ElementAtOrDefault(2);



21. Sum vs Average in LINQ

Sum: Computes the sum of elements in a collection.

Example:

var total = numbers.Sum();


Average: Computes the average of elements in a collection.

Example:

var avg = numbers.Average();



22. Min vs Max in LINQ

Min: Returns the smallest element in a collection.

Example:

var min = numbers.Min();


Max: Returns the largest element in a collection.

Example:

var max = numbers.Max();

These are key differences and comparisons between various LINQ methods, which you can use to filter, transform, and aggregate data in collections.


Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced