0% found this document useful (0 votes)
2 views

C# .net interview topics

The document outlines important C# .Net MVC interview topics, focusing on Object-Oriented Programming (OOP) principles such as encapsulation, inheritance, polymorphism, and abstraction. It also compares abstract classes and interfaces, discusses the use of virtual, override, and sealed keywords, and explains delegates and events in C#. Key differences and use cases for each concept are provided to aid understanding.

Uploaded by

pawarpooja3598
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C# .net interview topics

The document outlines important C# .Net MVC interview topics, focusing on Object-Oriented Programming (OOP) principles such as encapsulation, inheritance, polymorphism, and abstraction. It also compares abstract classes and interfaces, discusses the use of virtual, override, and sealed keywords, and explains delegates and events in C#. Key differences and use cases for each concept are provided to aid understanding.

Uploaded by

pawarpooja3598
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

C# .

Net MVC Important topics for the interview

Starting from oops:---------


1. Object-Oriented Programming (OOP) in C# is a programming paradigm based on the
concept of objects, which encapsulate data and behavior. C# is a fully object-oriented
language, meaning it uses OOP principles extensively to design and structure applications.

Core OOP Concepts in C#:

1. Class and Object

 Class: A blueprint for creating objects. It defines properties (data) and methods
(behavior).
 Object: An instance of a class. It represents a specific entity created from the class
blueprint.

Example:

csharp
CopyEdit
// Class definition
public class Car
{
public string Brand; // Property
public int Speed;

public void Drive() // Method


{
Console.WriteLine($"{Brand} is driving at {Speed} km/h.");
}
}

// Object creation
class Program
{
static void Main()
{
Car car = new Car(); // Object
car.Brand = "Toyota";
car.Speed = 120;
car.Drive();
}
}

2. Encapsulation
Encapsulation is the bundling of data (fields) and methods that operate on that data into a
single unit (class) while restricting access to some components.

 Achieved using access modifiers like private, public, protected, internal.


 Protects the data by hiding implementation details and exposing only necessary parts.

Example:

csharp
CopyEdit
public class Person
{
private string name; // Encapsulated field

// Public getter and setter


public string Name
{
get { return name; }
set { name = value; }
}
}

class Program
{
static void Main()
{
Person person = new Person();
person.Name = "John"; // Accessing through property
Console.WriteLine(person.Name);
}
}

3. Inheritance

Inheritance allows a class (child/derived class) to inherit properties and methods from another
class (parent/base class). It promotes code reusability.

 Base Class: The class being inherited from.


 Derived Class: The class inheriting from the base class.

Example:

csharp
CopyEdit
public class Animal
{
public void Eat()
{
Console.WriteLine("This animal eats food.");
}
}

public class Dog : Animal // Dog inherits Animal


{
public void Bark()
{
Console.WriteLine("The dog barks.");
}
}

class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Inherited method
dog.Bark(); // Dog's own method
}
}

4. Polymorphism

Polymorphism means "many forms." It allows methods in a class to have different


implementations based on the context.

Two Types of Polymorphism:

1. Compile-time Polymorphism (Method Overloading):


o Achieved by defining multiple methods with the same name but different
parameter lists.

Example:

csharp
CopyEdit
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)


{
return a + b;
}
}

2. Run-time Polymorphism (Method Overriding):


o Achieved by overriding a base class method in a derived class using the
virtual and override keywords.

Example:

csharp
CopyEdit
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("The animal makes a sound.");
}
}

public class Dog : Animal


{
public override void Speak()
{
Console.WriteLine("The dog barks.");
}
}

class Program
{
static void Main()
{
Animal animal = new Dog();
animal.Speak(); // Output: The dog barks.
}
}

5. Abstraction

Abstraction is the process of hiding implementation details and exposing only the essential
features.

 Achieved using abstract classes and interfaces in C#.

Abstract Class Example:

csharp
CopyEdit
public abstract class Shape
{
public abstract void Draw(); // Abstract method
}

public class Circle : Shape


{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}

Interface Example:

csharp
CopyEdit
public interface IShape
{
void Draw();
}

public class Rectangle : IShape


{
public void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
}

Comparison of Abstract Class and Interface

Feature Abstract Class Interface


Inheritance Single inheritance Multiple inheritance
Members Can have fields, methods, properties Only methods and properties
Accessibility Modifiers Supported Not supported

Summary of OOP Principles:

1. Encapsulation: Hides internal details of objects.


2. Inheritance: Allows code reuse between classes.
3. Polymorphism: Provides flexibility by using methods in different ways.
4. Abstraction: Simplifies design by focusing on what objects do instead of how they
do it

#------------------interface vs abstract class:-

The choice between abstract classes and interfaces in C# depends on the design and use
case. Here's a detailed comparison to help you understand their differences and use cases:

1. Definition

 Abstract Class: A class that can have both abstract methods (without
implementation) and concrete methods (with implementation). It is used to provide a
base class for other classes.
 Interface: A contract that defines only method signatures, properties, events, or
indexers, with no implementation. A class implementing an interface must provide its
implementation.

2. Syntax

Abstract Class:
csharp
CopyEdit
public abstract class Shape
{
public abstract void Draw(); // Abstract method (no implementation)
public void Display() // Concrete method (with implementation)
{
Console.WriteLine("This is a shape.");
}
}

Interface:

csharp
CopyEdit
public interface IShape
{
void Draw(); // No implementation allowed
}

3. Key Differences

Feature Abstract Class Interface


Supports single inheritance Supports multiple inheritance (a class can
Inheritance
only. implement multiple interfaces).
Methods cannot have implementation (until
Default Can have concrete methods
C# 8.0, which introduced default
Implementation with implementation.
implementations in interfaces).
Can use public,
All members are implicitly public and
Access Modifiers protected, or other
cannot have access modifiers.
modifiers.
Can have fields, constants, Cannot have fields; only methods,
Fields
and variables. properties, events, or indexers.
Constructors Can have constructors. Cannot have constructors.
Use when you want to share
Use when you want to define a contract that
When to Use code between related
unrelated classes must follow.
classes.
Slightly faster than
Slightly slower due to method dispatch
Performance interfaces as they are tightly
overhead (indirect calls).
coupled.

4. Usage Examples

Abstract Class Example:

csharp
CopyEdit
public abstract class Animal
{
public abstract void Speak(); // Abstract method
public void Sleep() // Concrete method
{
Console.WriteLine("Sleeping...");
}
}

public class Dog : Animal


{
public override void Speak()
{
Console.WriteLine("Dog barks.");
}
}

class Program
{
static void Main()
{
Animal dog = new Dog();
dog.Speak(); // Output: Dog barks.
dog.Sleep(); // Output: Sleeping...
}
}

Interface Example:

csharp
CopyEdit
public interface IVehicle
{
void Start();
void Stop();
}

public class Car : IVehicle


{
public void Start()
{
Console.WriteLine("Car is starting...");
}

public void Stop()


{
Console.WriteLine("Car is stopping...");
}
}

class Program
{
static void Main()
{
IVehicle car = new Car();
car.Start(); // Output: Car is starting...
car.Stop(); // Output: Car is stopping...
}
}

5. When to Use What


Use an Abstract Class when:

1. You need to provide a base class with common functionality for related classes.
2. You want to include both abstract methods (to be implemented by derived classes)
and concrete methods (to provide shared logic).
3. You want to define fields or state that will be shared among derived classes.

Use an Interface when:

1. You need to define a contract that unrelated classes must follow.


2. You need multiple inheritance (since a class can implement multiple interfaces but
inherit only one class).
3. You want to avoid coupling between the implementing class and the interface.

6. Abstract Class and Interface Together

You can combine both for more flexible designs. For example:

csharp
CopyEdit
public interface IWalkable
{
void Walk();
}

public abstract class Animal


{
public abstract void Eat();
}

public class Dog : Animal, IWalkable


{
public override void Eat()
{
Console.WriteLine("Dog eats food.");
}

public void Walk()


{
Console.WriteLine("Dog walks.");
}
}

class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Output: Dog eats food.
dog.Walk(); // Output: Dog walks.
}
}
Summary

Abstract Class Interface


Use when classes share common functionality. Use to define a contract for unrelated classes.
Supports fields and constructors. Cannot have fields or constructors.
Single inheritance. Supports multiple inheritance.

Let me know if you'd like further clarification or examples!

#------------ virtual, Override and sealed keywords:-

These three keywords are used in the context of method overriding in C#, enabling
polymorphism and defining how methods can be overridden or restricted.

1. Virtual

 A virtual keyword is used to allow a method in the base class to be overridden in


derived classes.
 By default, methods are not virtual in C#. To override a method in a child class, it
must be declared as virtual in the parent class.

Key Points:

 Can only be applied to methods, properties, or events.


 A virtual method in the base class can provide a default implementation, which can
then be overridden by derived classes.

Example:

csharp
CopyEdit
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Display method in BaseClass.");
}
}

public class DerivedClass : BaseClass


{
public override void Display()
{
Console.WriteLine("Display method in DerivedClass.");
}
}

class Program
{
static void Main()
{
BaseClass obj = new DerivedClass();
obj.Display(); // Output: Display method in DerivedClass.
}
}

2. Override

 The override keyword is used in a derived class to provide a new implementation for
a virtual or abstract method defined in the base class.
 The overridden method in the derived class must have the same signature as the
method in the base class.

Key Points:

 The override method replaces the base class implementation.


 The base class method must be marked as virtual or abstract to allow overriding.

Example:

csharp
CopyEdit
public class BaseClass
{
public virtual void Greet()
{
Console.WriteLine("Hello from BaseClass!");
}
}

public class DerivedClass : BaseClass


{
public override void Greet()
{
Console.WriteLine("Hello from DerivedClass!");
}
}

class Program
{
static void Main()
{
BaseClass obj = new DerivedClass();
obj.Greet(); // Output: Hello from DerivedClass!
}
}
3. Sealed

 The sealed keyword is used to prevent further overriding of a method in derived


classes.
 When a method in a derived class is marked as sealed, it cannot be overridden in any
further derived classes.

Key Points:

 Can only be applied to methods that override a base class method.


 Used to restrict polymorphism when needed.

Example:

csharp
CopyEdit
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Display method in BaseClass.");
}
}

public class DerivedClass : BaseClass


{
public sealed override void Display()
{
Console.WriteLine("Display method in DerivedClass.");
}
}

public class FurtherDerivedClass : DerivedClass


{
// Attempting to override `Display` here will result in a compile-time
error.
}

class Program
{
static void Main()
{
DerivedClass obj = new DerivedClass();
obj.Display(); // Output: Display method in DerivedClass.
}
}

Key Differences Between the Keywords

Keyword Usage Purpose


Used in the base class to allow derived Enables polymorphism by providing a
Virtual
classes to override a method. base implementation.
Used in the derived class to override a Provides a new implementation for the
Override
virtual/abstract method. base method.
Keyword Usage Purpose
Used in the derived class to restrict further Stops polymorphism for a method in
Sealed
overriding. further derived classes.

Real-World Analogy

 Virtual: A parent gives children permission to customize a rule, but provides a


default rule.
 Override: A child customizes the parent's rule.
 Sealed: The child finalizes the rule, preventing any further customization by future
generations

Delegates and Events:-

Delegates and events are fundamental concepts in C#, enabling callback mechanisms,
communication, and event-driven programming.

1. Delegates

Definition

A delegate is a type-safe function pointer that holds a reference to a method. It allows


methods to be passed as parameters and executed dynamically.

Key Features:

 Delegates are type-safe and ensure the method signature matches.


 They can hold references to single or multiple methods (multicast delegates).
 Delegates can be used to implement callbacks.

Syntax

Declare a delegate:

csharp
CopyEdit
public delegate void MyDelegate(string message); // Declaring a delegate

Example:

csharp
CopyEdit
// Delegate Declaration
public delegate void PrintDelegate(string message);

class Program
{
public static void PrintMessage(string msg)
{
Console.WriteLine(msg);
}

public static void PrintUppercaseMessage(string msg)


{
Console.WriteLine(msg.ToUpper());
}

static void Main()


{
// Delegate Instance
PrintDelegate del = PrintMessage;

// Calling the delegate


del("Hello, Delegates!"); // Output: Hello, Delegates!

// Multicast Delegate
del += PrintUppercaseMessage; // Add another method
del("Hello, Delegates!");
// Output:
// Hello, Delegates!
// HELLO, DELEGATES!
}
}

2. Events

Definition

An event is a wrapper around a delegate that provides a publisher-subscriber model. It


ensures that only the event owner (publisher) can raise the event, while other classes
(subscribers) can register their handlers.

Key Features:

 Events use delegates internally.


 Events ensure encapsulation by restricting access to the invoke operation (only the
publisher can invoke the event).
 Events are typically used in GUI programming and other event-driven architectures.
Syntax

Declare an event:

csharp
CopyEdit
public delegate void NotifyDelegate(string message);
public class Publisher
{
public event NotifyDelegate OnNotify; // Declaring an event
}

Example:
csharp
CopyEdit
// Step 1: Declare a delegate
public delegate void Notify(string message);

// Step 2: Declare a publisher class


public class Publisher
{
public event Notify OnNotify; // Declare an event

public void NotifySubscribers(string msg)


{
OnNotify?.Invoke(msg); // Raise the event
}
}

// Step 3: Declare a subscriber class


public class Subscriber
{
public void ShowMessage(string message)
{
Console.WriteLine($"Subscriber received: {message}");
}
}

class Program
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();

// Subscribe to the event


publisher.OnNotify += subscriber.ShowMessage;

// Trigger the event


publisher.NotifySubscribers("Hello, Events!"); // Output:
Subscriber received: Hello, Events!
}
}
Differences Between Delegates and Events
Aspect Delegate Event

A mechanism to enable publisher-subscriber


Definition A type-safe function pointer.
communication.

Cannot be directly invoked outside the


Access Can be directly invoked.
declaring class.

No restrictions; can be modified by Encapsulated; only the publisher can invoke


Encapsulation
external code. the event.

Used for callbacks or passing methods


Use Case Used for event-driven programming.
as parameters.

Multicast Delegates with Events

Events can use multicast delegates, meaning multiple subscribers can handle a single event.

Example:
csharp
CopyEdit
public delegate void Notify(string message);

public class Publisher


{
public event Notify OnNotify; // Event declaration

public void NotifySubscribers(string msg)


{
OnNotify?.Invoke(msg);
}
}

public class Subscriber


{
public void ShowMessage(string message)
{
Console.WriteLine($"Subscriber 1 received: {message}");
}

public void AnotherMessageHandler(string message)


{
Console.WriteLine($"Subscriber 2 received: {message}");
}
}

class Program
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
// Multiple handlers for the same event
publisher.OnNotify += subscriber.ShowMessage;
publisher.OnNotify += subscriber.AnotherMessageHandler;

publisher.NotifySubscribers("Event raised!");
// Output:
// Subscriber 1 received: Event raised!
// Subscriber 2 received: Event raised!
}
}

Summary

 Delegates: Function pointers used to dynamically call methods.


 Events: A mechanism to raise notifications and allow subscribers to respond.

Overloading and Overriding:-

Both overloading and overriding are key concepts in polymorphism in object-oriented


programming. However, they serve different purposes and are implemented differently.

1. Method Overloading

Method overloading allows multiple methods in the same class to have the same name but
different parameters (by type, number, or both).

Key Features:

 Happens within the same class.


 Methods must have different signatures (number or type of parameters).
 Does not depend on inheritance.
 It is an example of compile-time polymorphism (also known as static polymorphism).

Example:
csharp
CopyEdit
class Calculator
{
public int Add(int a, int b)
{
return a + b; // Adds two integers
}

public double Add(double a, double b)


{
return a + b; // Adds two doubles
}

public int Add(int a, int b, int c)


{
return a + b + c; // Adds three integers
}
}

class Program
{
static void Main()
{
Calculator calc = new Calculator();

Console.WriteLine(calc.Add(2, 3)); // Output: 5


Console.WriteLine(calc.Add(2.5, 3.5)); // Output: 6
Console.WriteLine(calc.Add(1, 2, 3)); // Output: 6
}
}

Key Points About Overloading:

 You can overload methods by changing:


o The number of parameters.
o The type of parameters.
o The order of parameters.
 Return type does not matter in method overloading alone.

2. Method Overriding

Method overriding allows a derived class to provide a new implementation for a method
that is already defined in its base class.

Key Features:

 Requires inheritance.
 The base class method must be marked as virtual, abstract, or override.
 The derived class method must use the override keyword.
 It is an example of runtime polymorphism (also known as dynamic polymorphism).

Example:
csharp
CopyEdit
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound.");
}
}

class Dog : Animal


{
public override void Speak()
{
Console.WriteLine("Dog barks.");
}
}

class Program
{
static void Main()
{
Animal animal = new Animal();
animal.Speak(); // Output: Animal makes a sound.

Animal dog = new Dog();


dog.Speak(); // Output: Dog barks.
}
}

Key Points About Overriding:

 The method signature (name, parameters, return type) must be the same as in the base
class.
 The base method must be declared as virtual or abstract to allow overriding.
 The overridden method in the derived class must use the override keyword.
 The base method implementation can still be accessed using the base keyword.

Key Differences Between Overloading and Overriding


Aspect Overloading Overriding

Defining multiple methods with the same Redefining a method from the base
Definition
name but different parameter lists. class in the derived class.

Inheritance Does not require inheritance. Requires inheritance.

Achieved at compile-time (static Achieved at runtime (dynamic


Compile/Runtime
polymorphism). polymorphism).

Parameters Must differ in type, number, or order. Must have the same signature.

Requires virtual (base) and


Keywords No special keywords required.
override (derived).
Aspect Overloading Overriding

Increases method flexibility for different Allows a derived class to change the
Purpose
input types or parameter counts. base class behavior.

Combined Example

To see the contrast between overloading and overriding:

csharp
CopyEdit
class Parent
{
public virtual void Show()
{
Console.WriteLine("Parent's Show method");
}
}

class Child : Parent


{
// Overriding
public override void Show()
{
Console.WriteLine("Child's Show method");
}

// Overloading
public void Show(string message)
{
Console.WriteLine($"Child's overloaded Show method: {message}");
}
}

class Program
{
static void Main()
{
Parent parent = new Parent();
parent.Show(); // Output: Parent's Show method

Child child = new Child();


child.Show(); // Output: Child's Show method
child.Show("Hello"); // Output: Child's overloaded Show method:
Hello
}
}

Summary

 Overloading: Same method name, different parameters, no inheritance required.


 Overriding: Same method name, same signature, inheritance required, and provides
polymorphic behavior
Data Structurees:-

Collections:- List<T>, Dictionary<k,v>,HashSet<T>, Queue,


stack)

In C#, collections are used to store and manipulate groups of related objects efficiently.
Here's a breakdown of commonly used generic collections in .NET, including List<T>,
Dictionary<K,V>, HashSet<T>, Queue<T>, and Stack<T>.

1. List<T>

 Definition: A generic collection that represents a dynamic array. It allows duplicate


elements and provides indexed access.
 Key Features:
o Maintains the order of elements.
o Allows duplicate values.
o Supports random access using an index.
o Automatically resizes when the capacity is exceeded.

Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4); // Add an element
numbers.Insert(1, 10); // Insert an element at index 1

foreach (int number in numbers)


{
Console.WriteLine(number);
}
// Output: 1, 10, 2, 3, 4
}
}

2. Dictionary<K, V>

 Definition: A generic collection that stores key-value pairs. Each key must be unique, and
keys are used to access the associated values.
 Key Features:
o Fast lookups using keys.
o Keys must be unique, but values can be duplicate.
o Does not maintain the order of elements.

Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Dictionary<int, string> students = new Dictionary<int, string>
{
{ 1, "Alice" },
{ 2, "Bob" },
{ 3, "Charlie" }
};

students[4] = "Diana"; // Add a new key-value pair

foreach (var kvp in students)


{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
// Output:
// Key: 1, Value: Alice
// Key: 2, Value: Bob
// Key: 3, Value: Charlie
// Key: 4, Value: Diana
}
}

3. HashSet<T>

 Definition: A collection that stores unique elements and offers high-performance lookups.
 Key Features:
o Does not allow duplicate elements.
o Does not maintain the order of elements.
o Optimized for set operations like union, intersection, and difference.

Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
HashSet<int> set = new HashSet<int> { 1, 2, 3, 4 };

set.Add(4); // Duplicate value - ignored


set.Add(5); // Unique value - added

foreach (int item in set)


{
Console.WriteLine(item);
}
// Output (order may vary): 1, 2, 3, 4, 5
}
}

4. Queue<T>

 Definition: A first-in, first-out (FIFO) collection of elements. Items are added at the back and
removed from the front.
 Key Features:
o Elements are processed in the order they were added.
o Commonly used for sequential processing tasks.

Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Queue<string> queue = new Queue<string>();

queue.Enqueue("Task1");
queue.Enqueue("Task2");
queue.Enqueue("Task3");

Console.WriteLine(queue.Dequeue()); // Removes and returns the


first element: Task1
Console.WriteLine(queue.Peek()); // Returns the next element
without removing: Task2
}
}
// Output:
// Task1
// Task2
5. Stack<T>

 Definition: A last-in, first-out (LIFO) collection of elements. Items are added to and removed
from the top of the stack.
 Key Features:
o Elements are processed in reverse order (last added is the first removed).
o Commonly used for backtracking scenarios like navigating back in a browser.

Example:
csharp
CopyEdit
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
Stack<string> stack = new Stack<string>();

stack.Push("Page1");
stack.Push("Page2");
stack.Push("Page3");

Console.WriteLine(stack.Pop()); // Removes and returns the top


element: Page3
Console.WriteLine(stack.Peek()); // Returns the top element without
removing: Page2
}
}
// Output:
// Page3
// Page2

Comparison Table
Collection Allows Duplicates Maintains Order Key Feature

List<T> Yes Yes Dynamic array with indexed access.

Dictionary<K,V> No (keys only) No Key-value pairs with fast lookups.

HashSet<T> No No Ensures unique elements.

Queue<T> Yes Yes (FIFO) First-in, first-out collection.

Stack<T> Yes Yes (LIFO) Last-in, first-out collection.

When to Use Each?

 List<T>: When you need a dynamic array and order matters.


 Dictionary<K,V>: When you need fast lookups using a key-value pair.
 HashSet<T>: When you need unique elements and performance is critical.
 Queue<T>: When you need FIFO processing.
 Stack<T>: When you need LIFO processing, such as undo operations.

Le

LINQ (language integrated Query):--

LINQ (Language Integrated Query) in C#

LINQ stands for Language Integrated Query, a powerful feature in C# that enables
querying data in a consistent, readable, and type-safe manner, regardless of the data source
(e.g., collections, databases, XML, etc.). It allows you to write queries directly in C# without
requiring SQL, XPath, or other domain-specific languages.

Key Features of LINQ

1. Unified Query Syntax: Query various data sources (collections, databases, XML) using the
same syntax.
2. Strongly Typed: LINQ queries are type-checked at compile time, reducing runtime errors.
3. Readable and Declarative: LINQ syntax is similar to SQL, making it easier to understand.
4. Deferred Execution: Many LINQ operations are executed only when the result is iterated
(e.g., using foreach).
5. Integration with .NET: Fully integrated into the .NET framework and works seamlessly with
C# collections and other data sources.

LINQ Syntax

LINQ supports two syntaxes:

1. Query Syntax: Similar to SQL, easier to read.


2. Method Syntax: Uses extension methods, more concise.

Common LINQ Operations

1. Where (Filtering)

Filters elements based on a condition.


var evenNumbers = numbers.Where(n => n % 2 == 0);

2. Select (Projection)

Transforms or projects data into a new form.

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

3. OrderBy (Sorting)

Sorts data in ascending or descending order.

var sortedNames = names.OrderBy(n => n);

4. GroupBy (Grouping)

Groups data based on a key.

var groups = people.GroupBy(p => p.City);

5. Join (Joining)

Combines data from two sequences based on a key.

var joinedData = customers.Join(orders,


c => c.Id,
o => o.CustomerId,
(c, o) => new { c.Name, o.OrderDate });

6. Aggregate (Aggregations)

Performs aggregation operations (e.g., sum, average, etc.).

var total = numbers.Aggregate((sum, n) => sum + n);

Examples

1. LINQ with Collections

Using Query Syntax:


using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };

// Query Syntax
var evenNumbers = from n in numbers
where n % 2 == 0
select n;

foreach (var num in evenNumbers)


{
Console.WriteLine(num); // Output: 2, 4, 6
}
}
}
Using Method Syntax:
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
evenNumbers.ForEach(Console.WriteLine); // Output: 2, 4, 6

2. LINQ with Objects

using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
static void Main()
{
var people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 35 }
};

// Find people older than 30


var result = from p in people
where p.Age > 30
select p;

foreach (var person in result)


{
Console.WriteLine(person.Name); // Output: Charlie
}
}
}

class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

3. LINQ to SQL

Using LINQ to query a database (with Entity Framework):

using (var context = new MyDbContext())


{
var customers = from c in context.Customers
where c.City == "Pune"
select c;
foreach (var customer in customers)
{
Console.WriteLine(customer.Name);
}
}

4. LINQ to XML

Querying XML data with LINQ:

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
static void Main()
{
string xml = @"<Books>
<Book><Title>C#
Programming</Title><Price>500</Price></Book>
<Book><Title>LINQ
Basics</Title><Price>300</Price></Book>
</Books>";

XDocument doc = XDocument.Parse(xml);

var titles = from b in doc.Descendants("Book")


where (int)b.Element("Price") > 400
select b.Element("Title").Value;

foreach (var title in titles)


{
Console.WriteLine(title); // Output: C# Programming
}
}
}

Advantages of LINQ

1. Consistency: Same syntax for different data sources.


2. Readability: Queries are easy to understand and maintain.
3. Compile-time Safety: Errors are caught during compilation, not runtime.
4. Integration: Fully integrated with the .NET framework.
5. Productivity: Reduces boilerplate code for data operations.

Disadvantages

1. Can sometimes be less performant than raw SQL for complex queries.
2. Debugging LINQ expressions can be challenging.
3. Limited control over SQL queries generated in LINQ-to-SQL.
When to Use LINQ?

 When working with in-memory collections like List<T> or Array.


 When querying databases (LINQ to SQL/Entity Framework).
 When working with XML or JSON data.

Let me know if you'd like specific examples or a deeper dive into any of these concepts!

IEnumerable vs IQueryable:-

Both IEnumerable and IQueryable are interfaces in C# used for data querying and
manipulation. However, they have significant differences in terms of execution,
performance, and use cases.

1. IEnumerable

Namespace: System.Collections
Definition: It is used to iterate over a collection of objects, such as arrays, lists, or other in-
memory data.

Key Characteristics

1. In-Memory Execution: Executes queries on in-memory collections (e.g., List<T>,


Array).
2. Deferred Execution: Query execution is deferred until the data is accessed (e.g.,
using foreach).
3. Client-Side Filtering: Filters the data on the client-side, meaning the entire dataset is
loaded into memory before filtering.
4. Limited Use in LINQ to SQL/EF: Primarily used for LINQ-to-Objects, as it doesn't
translate queries into SQL.
5. Forward-Only Iteration: Supports forward-only enumeration of a collection.

Use Cases

 Best for querying in-memory collections like List<T>, Dictionary<K,V>, etc.


 Suitable for small datasets where filtering on the client-side is acceptable.

Example with IEnumerable

csharp
CopyEdit
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };

// IEnumerable
IEnumerable<int> evenNumbers = numbers.Where(n => n % 2 == 0); //
Filters in-memory

foreach (var num in evenNumbers)


{
Console.WriteLine(num); // Output: 2, 4, 6
}
}
}

2. IQueryable

Namespace: System.Linq
Definition: It is used for querying data sources that implement LINQ providers, such as
databases, and translates LINQ queries into specific queries (e.g., SQL for databases).

Key Characteristics

1. Query Execution on Data Source: Executes the query on the server-side (e.g., SQL
Server).
2. Deferred Execution: Like IEnumerable, queries are executed when accessed.
3. Efficient Filtering: Only the required data is fetched from the data source, reducing
memory usage.
4. Used in LINQ to SQL/EF: Commonly used for querying remote databases through
LINQ to SQL or Entity Framework.
5. Complex Query Translation: Converts LINQ queries to SQL or equivalent for the
underlying data source.

Use Cases

 Best for querying large datasets stored in databases or other external sources.
 Preferred when working with LINQ to SQL or Entity Framework to optimize data
retrieval.

Example with IQueryable

csharp
CopyEdit
using System;
using System.Linq;
using System.Data.Entity;

class Program
{
static void Main()
{
using (var context = new MyDbContext())
{
// IQueryable
IQueryable<Customer> customersFromPune = context.Customers
.Where(c => c.City == "Pune"); // Filters on the database
server

foreach (var customer in customersFromPune)


{
Console.WriteLine(customer.Name);
}
}
}
}

public class MyDbContext : DbContext


{
public DbSet<Customer> Customers { get; set; }
}

public class Customer


{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}

Key Differences

Feature IEnumerable IQueryable


Execution
Client-side (in-memory). Server-side (data source).
Location
Deferred Yes (data is not fetched until Yes (query executed only when
Execution accessed). iterated).
Inefficient for large datasets (loads Efficient for large datasets (filters
Performance
entire dataset). data at the source).
LINQ-to-SQL, Entity Framework,
Use Case LINQ-to-Objects (e.g., Lists, Arrays).
or querying external sources.
Query Cannot translate queries to SQL or Translates LINQ to SQL or
Translation other query languages. equivalent for the data source.
Namespace System.Collections System.Linq

When to Use

 Use IEnumerable:
o When working with in-memory collections.
o For small datasets where performance is not a concern.
o In cases where the data is already loaded.
 Use IQueryable:
o When querying large datasets from databases.
o When working with Entity Framework or LINQ-to-SQL.
o For better performance and efficiency in data retrieval.

Practical Comparison

Example with IEnumerable (Client-Side Filtering)

csharp
CopyEdit
IEnumerable<Customer> customers = context.Customers.ToList();
var filteredCustomers = customers.Where(c => c.City == "Pune"); // Entire
table loaded into memory

Example with IQueryable (Server-Side Filtering)

csharp
CopyEdit
IQueryable<Customer> customers = context.Customers;
var filteredCustomers = customers.Where(c => c.City == "Pune"); // Filters
at the database level

Key Takeaways

1. Use IEnumerable for in-memory collections.


2. Use IQueryable for querying external data sources like databases.
3. IQueryable is more efficient for large datasets as it fetches only the required data.

Let m

You might also like