Saturday, 9 August 2025

yield in c# 
 Certainly! The yield keyword in C# is used to simplify the creation of iterators. 
It allows you to return each element of a collection one at a time, without the need for an explicit collection or temporary storage. 
Here's a breakdown of how it works: 
 yield return: 
 This statement is used to return each element one at a time. 
 When the yield return statement is reached, the current location in the code is remembered, and execution is paused until the next element is requested. Example:
IEnumerable<int> GetEvenNumbers(int max)
{
    for (int i = 0; i <= max; i += 2)
    {
        yield return i;
    }
}
yield break:
This statement is used to end the iteration early. It stops the iteration and exits the method. Example:
IEnumerable<int> GetNumbersUntilNegative(int[] numbers)
{
    foreach (int number in numbers)
    {
        if (number < 0)
        {
            yield break;
        }
        yield return number;
    }
}
Benefits: Simplifies Code: Reduces the need for explicit state management and temporary collections.

Lazy Evaluation: Elements are generated on-the-fly, which can improve performance and reduce memory usage. 
Usage: Commonly used in methods that return IEnumerable<int> or IEnumerator<int>. Can be used in both synchronous and asynchronous methods (with IAsyncEnumerable). 
 In summary, the yield keyword in C# provides a convenient way to create iterators, making your code cleaner and more efficient.
Share:

Dispose Pattern (Advanced) for both managed and unmanaged resources

🔄 Dispose Pattern (Advanced) If your class holds both managed and unmanaged resources, implement the full dispose pattern:

public class MyResource : IDisposable
{
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);  // Prevent finalizer from running
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Dispose managed resources
            }

            // Release unmanaged resources
            disposed = true;
        }
    }

    ~MyResource()
    {
        Dispose(false);  // Finalizer only releases unmanaged resources
    }
}

📋 Best Practices ✅ Always use using for short-lived disposable objects. ✅ Implement IDisposable if your class owns disposable fields. ✅ Call GC.SuppressFinalize(this) in Dispose() if you have a finalizer. ✅ Make Dispose() idempotent — safe to call multiple times.
Share:

Saturday, 19 April 2025

Custom Immutable Class

Creating an immutable class in C# ensures that once an instance is created, its state cannot be modified. This is useful for Creating reliable and thread-safe objects. Here’s how you can achieve this: 

1- Use readonly fields and initialize them through the constructor. 
2- Avoid setters for properties. 
3- Mark the class as sealed to prevent inheritance (optional). Here’s a simple example:
public sealed class ImmutablePerson
{
    public readonly string FirstName { get; }
    public readonly string LastName { get; }

    public ImmutablePerson(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public string GetFullName()
    {
      return  $"{FirstName} {LastName}"
    }
}

var person = new ImmutablePerson("John", "Doe");
 Console.WriteLine(person.GetFullName());
In this example: 
1- The FirstName and LastName properties are read-only. 
2- The only way to set FirstName and LastName is through the constructor. 
3- The class is sealed to prevent modification through inheritance.
Share:

Multiple implementations of an interface with number of Services

All ManagerService, TeamLeaderService and EngineerService are registered with the DI container. 
 The EmployeeController constructor injects IEnumerable <ISalaryService >, allowing you to iterate through all registered implementations and call their Execute methods. Alright, so you've got multiple implementations of an interface, and you want to call a specific service based on some criteria. Here’s a more detailed approach to achieve this: Define Your Interface and Implementations:
public interface ISalaryService
{
    void Execute();
}

public class ManagerService : ISalaryService
{
    public float ExecuteSalary() => 10000 + (10000 * .50) ;
}

public class TeamLeaderService : ISalaryService
{
    public float ExecuteSalary() => 10000 + (10000 * .20);
}
public class EngineerService : ISalaryService
{
    public float ExecuteSalary() => 10000 + (10000 * .10);
}
Register Multiple Implementations with Named Options: You can use named registrations in the DI container to differentiate between the services.
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient <ISalaryService, ManagerService>(sp => new ManagerService());
        services.AddTransient<ISalaryService TeamLeaderService>(sp => new TeamLeaderService());
	services.AddTransient<Isalaryservice EngineerService>(sp => new EngineerService());
		
       services.AddTransient<Func<string, ISalaryService>>(serviceProvider => key =>
        {
            return key switch
            {
                "MA" => serviceProvider.GetService(),
                "TL" => serviceProvider.GetService(),
		"SE" => serviceProvider.GetService(),
                _ => throw new KeyNotFoundException()
            };
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configuration code
    }
}
Resolve Specific Implementation: Use a factory pattern to resolve and call the specific service based on a key.
public class EmployeeController : ControllerBase
{
    private readonly Func<string, ISalaryService> _serviceFactory;

    public EmployeeController(Func<string, ISalaryService> serviceFactory)
    {
        _serviceManager = serviceManager;
    }

    [HttpGet("ExecuteSalaryService")]
    public IActionResult ExecuteSalaryService([FromQuery] string serviceName)
    {
        var service = _serviceManager(serviceName);
        flot salary=service.ExecuteSalary();
	var data=new { totalSal=salary};
        return Ok(data);
    }
}
In this example:All ManagerService, TeamLeaderService and EngineerService are registered with the DI container.  A factory delegate (Func<string, ISalaryService >) is registered to resolve the service based on a key.  EmployeeController injects the factory and uses it to call the specific service based on the serviceName query parameter.
Share:

Monday, 5 August 2024

intview questions

using System;
public class HelloWorld
{
    public static void Main(string[] args)
    {
        A obja=new B();
        obja.Method();
    }
}

public class A{

    static A(){
        Console.WriteLine("construct static A");
    }

    public A(){
         Console.WriteLine("construct default A");
    }

    public void Method(){
         Console.WriteLine("called method of A");
    }
}

public class B : A
{
    static B(){
        Console.WriteLine("construct static B");
    }

    public B(){
         Console.WriteLine("construct default B");
    }

    public void Method(){
         Console.WriteLine("called method of B");
    }
}

 

Output :

construct static B

construct static A

construct default A

construct default B

called method of A
Share:

Thursday, 18 July 2024

Using Orderby ascending and Orderby descending to sort array javascript

Array.prototype.orderby=function()
{
  let self=this;
  let arr=[self[0]], i=1;
    for(;i<self.length; i++)
    {
      let index=arr.findIndex(f=>f > self[i]);
      arr.splice(index==-1?arr.length: index, 0, self[i]);
    }
  return arr;
}

Array.prototype.orderdescby=function()
{ 
 let self=this;
 let arr=[self[0]], i=1;
    for(;i<self.length; i++)
    {
        let index=arr.findIndex(f=>f < self[i]);
        arr.splice(index==-1?arr.length:index,0,self[i]);
    }
 return arr;
}

const points = [40, 100, 1, 500, 25, 107,0];
console.log(points.orderby())
console.log(points.orderdescby())
Share:

Wednesday, 17 July 2024

Javascript String extend for new function.

Javascript String extend for new function.
First Approch:
String.prototype.toArray=function(){
   let arr=[];
   for(let ch of this){
    arr.push(ch);
	}
	return arr;
}

let name="suresh";
console.log(name.toArray()); //output   [ 's', 'u', 'r', 'e', 's', 'h' ]

Second Approch:
String.prototype.toArray=function(){
	return this.split('');
}

let name="suresh";
console.log(name.toArray()); //output   [ 's', 'u', 'r', 'e', 's', 'h' ]
Share:

Difference between functions and methods in JavaScript:

 

  1. JavaScript Functions:

    • A function is a block of code designed to perform a specific task.
    • It can be defined using the function keyword, followed by a name and optional parameters.
    • The body of the function is enclosed in curly braces.
    • Functions are executed when something calls or invokes them.
    • Example:
      function addName(a, b) {
          return a + " " + b;
      }
      console.log(addName("Suresh", "Sharma")); // Output: Suresh Sharma
      
  2. JavaScript Methods:

    • A method is a function associated with an object.
    • It is a property of an object that contains a function definition.
    • Methods are functions stored as object properties.
    • They can be accessed using the following syntax: object.methodName().
    • Methods operate on the data contained in a class (i.e., the object it belongs to).
    • Example:
      let employee = {
          empname: "Suresh Sharma",
          department: "Software",
          details: function () {
              return this.empname + " works in "+ this.department +" Department.";    }};
                     console.log(employee.details()); // Output: "Suresh Sharma works in Software Department."

In summary:

  • A function can stand alone and be called directly by its name.
  • A method is a function associated with an object property.
  • Methods implicitly pass the object on which they were called.



Share:

Tuesday, 16 July 2024

Higher-Order Components (HOCs) and render props

  1. HOCs (Higher-Order Components):

    • Scenario: When you want to share cross-cutting concerns (such as data fetching, authentication, or logging) across multiple components.
    • Use Cases:
      • Data Fetching: Wrap components with an HOC that fetches data and provides it as props.
      • Authentication: HOCs can handle user authentication and authorization checks.
      • Logging and Analytics: Wrap components to log events or track user interactions.
    • Example:
      • React Router uses HOCs for route authentication and navigation.
  2. Render Props:

    • Scenario: When you need dynamic, flexible rendering behavior within a component.
    • Use Cases:
      • Conditional Rendering: Render different UI components based on state or props.
      • Customizable Behavior: Allow users of your component to inject their rendering logic.
      • Dynamic Children: Create components that can render different content dynamically.
    • Example:
      • Form libraries like Formik use render props to customize form rendering.
  3. Combining Both:

    • Sometimes, combining HOCs and render props provides maximum flexibility.
    • Scenario: When you want to share behavior (HOC) but allow customization (render props).
    • Use Cases:
      • Data Fetching with Custom Rendering: Use an HOC for data fetching and a render prop for custom rendering.
      • Composing Multiple Behaviors: Chain HOCs and render props together for complex components.
    • Example:
      • React Query library combines HOCs and render props for data fetching and caching.

In summary:

  • HOCs are great for cross-cutting concerns and reusable behavior.
  • Render props excel when you need dynamic rendering and customization.


Share:

Monday, 15 July 2024

Differences between forEach(), some(), and every() in JavaScript when working with arrays

forEach():
The forEach() method iterates over each element in an array and executes a provided function for each element. It does not return a new array; instead, it performs side effects (e.g., modifying elements, logging, etc.). Use forEach() when you want to perform an action on each element without creating a new array.
Example: JavaScript
const numbers = [1, 2, 3, 4];
numbers.forEach((num) => console.log(num));

some():
The some() method checks whether at least one element in the array satisfies a given condition (predicate). It returns true if any element passes the test; otherwise, it returns false. Use some() when you want to check if any element meets a specific condition.
Example: JavaScript
const strarr = ["method", "checks", "whether"];
const isFound = strarr.some((item) => item==="whether");
console.log(isFound); // true
const isNotFound = strarr.some((item) => item==="ram");
console.log(isNotFound); // false

every():
The every() method checks whether all elements in the array satisfy a given condition (predicate). It returns true if all elements pass the test; otherwise, it returns false. Use every() when you want to ensure that all elements meet a specific condition.
Example: JavaScript
const numbers = [1, 2, 3, 4];
const allPositive = numbers.every((num) => num > 0);
console.log(allPositive); // true

In summary:

Use forEach() for side effects (e.g., logging, modifying elements).
Use some() to check if any element meets a condition.
Use every() to ensure all elements satisfy a condition.
Share:

Friday, 12 July 2024

Javascript Promise

JavaScript Promises: 
  Promise.all(): The Promise.all() method accepts an iterable (such as an array of promises) and returns a single promise. It resolves when all input promises have resolved successfully. If any of the input promises reject, the returned promise will also reject. Example: JavaScript
const promise1 = fetch('https://api.sureshsharma.net/data1');
const promise2 = fetch('https://api.sureshsharma.net/data2');

Promise.all([promise1, promise2])
  .then(([response1, response2]) => {
    // Handle both responses here
  })
  .catch((error) => {
    // Handle errors
  });
Promise.race(): The Promise.race() method takes an iterable of promises and returns a new promise. It resolves or rejects as soon as the first promise in the iterable resolves or rejects. Useful for scenarios like setting a timeout for an operation. Example: JavaScript
const timeoutPromise = new Promise((resolve, reject) => {
  setTimeout(() => reject('Timeout'), 5000);
});

const fetchDataPromise = fetch('https://api.sureshsharma.net/data');

Promise.race([timeoutPromise, fetchDataPromise])
  .then((response) => {
    // Handle the first resolved promise (either timeout or data)
  })
  .catch((error) => {
    // Handle errors (timeout or fetch failure)
  });
Promise.finally(): The finally() method allows you to specify a callback that runs regardless of whether the promise is resolved or rejected. Useful for cleanup tasks (e.g., closing resources, resetting state). Example: JavaScript
fetchDataPromise
  .then((data) => {
    // Process data
  })
  .catch((error) => {
    // Handle errors
  })
  .finally(() => {
    // Cleanup or final actions
  });
Promise.any(): The Promise.any() method returns a promise that resolves with the value of the first fulfilled promise in the iterable. If all promises reject, it rejects with an array of rejection reasons. Useful when you want to proceed with the first successful result. Example: JavaScript
const promises = [promise1, promise2, promise3];

Promise.any(promises)
  .then((result) => {
    // Handle the first successful response
  })
  .catch((errors) => {
    // Handle all rejections
  });
  
Share:

Thursday, 11 July 2024

The differences and use cases for find, filter, map, reduce, and from in JavaScript

The differences and use cases for find, filter, map, reduce, and from in JavaScript:

find:
Purpose: Finds the first element in an array that satisfies a given condition. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const found = numbers.find(item => item === 3);
console.log(found); // 3
When to Use: When you need to locate a specific element based on a condition.

filter:
Purpose: Creates a new array with elements that pass a specified test. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
When to Use: To filter out elements that don’t meet a certain condition.

map:
Purpose: Creates a new array by applying a function to each element in the original array. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
When to Use: When you want to transform each element in an array.

reduce:
Purpose: Reduces an array to a single value by applying a function to each element. Usage: JavaScript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10
When to Use: For aggregating values (e.g., sum, product, concatenation).

from:
Purpose: Creates a new array from an iterable (e.g., string, Set, Map). Usage: JavaScript
const str = 'Hello';
const charArray = Array.from(str);
console.log(charArray); // ['H', 'e', 'l', 'l', 'o']
When to Use: When converting non-array iterables into arrays.
Share:

Saturday, 29 June 2024

Entity Framework Core Topics

Entity Framework Core interview questions you might encounter:

1.      How does Entity Framework Core handle data concurrency conflicts?

·         EF Core uses optimistic concurrency control. When multiple users try to modify the same record simultaneously, it checks if the record has changed since it was loaded. If so, it throws a DbUpdateConcurrencyException.

2.      What are the core differences between Entity Framework 6 and Entity Framework Core?

·         EF Core is lightweight, cross-platform, and designed for modern applications. It lacks some features of EF 6 (e.g., lazy loading, EDMX designer), but offers better performance and flexibility.

3.      How would you map a database schema to entities in Entity Framework Core?

·         Use data annotations or Fluent API to define relationships, keys, and constraints. Customize the model by configuring entity properties and navigation properties.

When optimizing performance in Entity Framework Core (EF Core), consider the following strategies:

Retrieve Only Necessary Data:

Fetch only the columns you need from the database. Use .Select() to project specific properties and minimize data retrieval.

Split Large Data Contexts:

Divide a large data context into smaller ones. This can improve performance by reducing the overhead of tracking entities.

Batch Updates:

For bulk updates, use batch operations (SaveChanges() with multiple entities). This reduces the number of database round trips.

Disable Change Tracking for Read-Only Queries:

If you’re querying data for read-only purposes, disable change tracking to avoid unnecessary overhead.

DbContext Pooling:

Reuse DbContext instances using pooling. This minimizes the cost of creating and disposing of contexts.

Use IQueryable Instead of IEnumerable:

Prefer IQueryable over IEnumerable for better query translation and execution.

Eager Loading:

Explicitly load related entities using .Include() to avoid lazy loading overhead.


DbContext pooling is a feature in Entity Framework Core (EF Core) that helps improve performance and resource utilization when working with database contexts. Let’s dive into the details:

What is DbContext?

DbContext is a fundamental class in EF Core. It represents a session with the database and provides an abstraction over the underlying database connection. It allows you to query, insert, update, and delete data.

Why Use DbContext Pooling?

Creating a new DbContext instance for every database operation can be expensive. It involves overhead such as connection establishment, model initialization, and change tracking setup.

DbContext pooling addresses this by reusing existing instances, reducing the overhead of creating new contexts.

How Does DbContext Pooling Work?

When you enable pooling, EF Core maintains a pool of pre-initialized DbContext instances.

When you request a context, it’s taken from the pool (if available) rather than creating a new one.

After use, the context is returned to the pool for reuse.

Enabling DbContext Pooling:

To enable pooling, set the UseDbContextPooling option in your DbContext configuration:

C#

services.AddDbContext<MyDbContext>(options =>

{

    options.UseSqlServer(connectionString);

    options.UseDbContextPooling();

});

DbContext pooling is most beneficial in scenarios with frequent short-lived database operations (e.g., web applications).

Be cautious with long-lived contexts (e.g., background services) as they may accumulate state over time.


Fluent API in Entity Framework Core (EF Core) allows you to configure domain classes and override conventions without modifying your entity classes directly. It provides fine-grained control over how your entities map to database tables.

Fluent API and DbContext Configuration:

The most powerful way to configure your model in EF Core is by overriding the OnModelCreating method in your derived context.

Within this method, you can use Fluent API to specify how entities map to tables, define relationships, and more.

Fluent API configuration has the highest precedence and overrides conventions and data annotations.


1.      Conventions:

o   Conventions are the default rules that EF Core follows to map your domain model to the database schema.

o   For example, EF Core assumes that a property named Id is the primary key, and it pluralizes entity names to find corresponding table names.

o   Conventions simplify development by providing sensible defaults.

2.      Data Annotations:

o   Data annotations are attributes you apply directly to your entity classes or properties.

o   They allow you to customize aspects of the model, such as specifying column names, defining keys, or setting data types.

o   Examples include [Key], [Column], and [MaxLength].

3.      Fluent API:

o   Fluent API provides a more flexible and explicit way to configure your model.

o   You override the OnModelCreating method in your DbContext and use fluent methods to define mappings, relationships, and other details.

o   It allows fine-grained control, such as specifying composite keys, unique constraints, and custom column names.

4.      Precedence:

o   When there’s a conflict between conventions, data annotations, and fluent configuration, fluent configuration wins.

o   If you explicitly configure something using fluent API, it overrides any conventions or data annotations related to the same aspect.

Fluent API in Entity Framework Core (EF Core), you can specify which properties form the composite key. Here’s an example:

Suppose we have an entity named Employee with properties Id and Name. We want to create a composite key using both properties. Here’s how you can do it:

C#

public class Employee 

{

    public int Id { get; set; }

    public string Name { get; set; }

}

 

public class YourContext : DbContext

{

    public DbSet<Employee> employee { get; set; }

 

    protected override void OnModelCreating(ModelBuilder modelBuilder)

    {

        modelBuilder.Entity<Employee>().HasKey(emp => new { emp.Id, emp.Name });

    }

}

In this example, the HasKey method specifies that the composite key consists of both Id and Name. This ensures uniqueness based on the combination of these properties

Share:

Monday, 24 June 2024

What is static

  • A static class cannot contain any non-static members except const and enum.
  • A static class cannot inherit from other classes except the Object class. 
  • A static classes cannot implement interfaces. 
  • A static classes cannot be inherited because they are implicitly sealed by default. 
  • A static class cannot contain any instance constructors. 
  • A static class cannot be explicitly marked as sealed because it is already sealed by default. 
  • A static class can contain enums. explicit private constructors are not allowed in a static class. 
  • Only a static constructor (implicitly private) can be defined. 
  • A static class cannot be instantiated; it is implicitly abstract. 
  • A non-static class can contain static methods. 
  • A static method can be accessed using the class name itself, without creating an object of the class. 
  • A non-static class can also contain a static constructor. 
  • A static class cannot contain any destructor. an indexer cannot be defined in a static class because indexers cannot be static.
Share:

ASP.NET MVC request life cycle:

In ASP.NET MVC, understanding the request life cycle is essential for building robust web applications. Let’s explore the key stages of the ASP.NET MVC request life cycle: 
 
  Routing: 
  • When a client makes a request (e.g., visits a URL), the routing module processes it. 
  • The routing module maps the requested URL to a specific controller action based on predefined routes. 
  • Routes are defined in the RouteConfig.cs (or Startup.cs for ASP.NET Core) file. 
MVC Handler: 
  • Once the route is determined, the MVC handler is responsible for creating the appropriate controller instance. 
  • The controller is instantiated, and the action method is invoked. Controller Action Execution: 
  • The controller’s action method processes the request. 
  • It interacts with the model (data) and prepares the data to be displayed. 
  • The action method returns an ActionResult (e.g., a view, JSON, or redirect). 
View Result: 
  • The view engine processes the view result returned by the action method. 
  • It locates the corresponding view file (.cshtml) based on conventions. 
  • The view is rendered, and dynamic data is injected into the HTML. 
View Engine and View: 
  • The view engine compiles the view into HTML. 
  • The final HTML content is sent as the response to the client. 
  • The client’s browser renders the page. 
Application_End (Optional): 
  • If the application pool recycles or certain thresholds are exceeded, the Application_End event in Global.asax.cs is fired. 
  • This event allows you to perform cleanup tasks before the application shuts down.
Share:

Frequency of character in string

Using Dictionary:
string input = "Mahindra Thar Armada";
Dictionary charFrequency = new Dictionary();

foreach (char c in input)
{
    if (charFrequency.ContainsKey(c))
    {
        charFrequency[c]++;
    }
    else
    {
        charFrequency[c] = 1;
    }
}

// Print the character frequencies
foreach (var pair in charFrequency)
{
    Console.WriteLine($"{pair.Key} - {pair.Value}");
}

Using Linq Query:
var charFrequency = input
    .GroupBy(c => c)
    .ToDictionary(g => g.Key, g => g.Count());

// Print the character frequencies
foreach (var pair in charFrequency)
{
    Console.WriteLine($"{pair.Key} - {pair.Value}");
}
Using JavaScript
const frequencyOfChar = (arr) => {
    return arr.reduce((total, letter) => {
        total[letter] ? total[letter]++ : (total[letter] = 1);
        return total;
    }, {});
};


let input="Mahindra Thar Armada";
let arr=[...input];
const result = frequencyOfChar(arr);
console.log(result); // {"M": 1,"a": 5,"h": 2, "i": 1, "n": 1, "d": 2, "r": 3, " ": 2, "T": 1, "A": 1, "m": 1 }
Share:

Saturday, 26 April 2014

Using Predicate and Func in linq using c#

//Creation of Predicate

Predicate<String> checkGreterthen5= x=> x.Length>5;

List<String> oLst=new List<string>();

oLst.Add("sa");

oLst.Add("saurabh");

String str = oLst.Find(checkGreterthen5);

Console.WriteLine(str);//Saurabh

//Creation of Func

delegate Double CalcAreaPointer(int r);

CalcAreaPointer _obj= r => 3.14 * r*r;

Double Area=_obj(5);

Func<double,double,double> _obj2=(r,e)=> 3.14 *r*e;

//Action<>

Double Area2 = _obj2(5,2);
Share:

Most Occurred Number in Integer Array using Linq using C#

String[] _numbers = { "2", "1", "3", "2", "4", "6", "2", "1", "4", "6", "6", "4", "8", "1", "3", "8" };
var _query2 = from n in _numbers
 group n by n into g
 select new
 {
 number = g.Key,
 count = g.Count()
 };
 var _MaxCount = _query2.Max(a => a.count);
 var mostOccurednumber = _query2
 .Where(g => g.count == _MaxCount)
 .Select(g => g.number);
Share:

Friday, 25 April 2014

Merging three array and take top 5 numbers using LINQ in C#

int[] _inputs1 = { 11,12, 13, 14, 15, 16, 17, 18, 169 };
int[] _inputs2 = { 11, 22, 33, 24, 25, 56, 67, 88, 99 };
int[] _inputs3 = { 1, 2, 3, 4, 5, 6, 7, 68, 98 };
Int32[] Concatenate=Input1.Concat(Input2).Concat(Input3).OrderByDescending(a=>a)
 .Take(5).ToArray();
foreach(int a in Concatenate)
{
 Console.writeline(a);
}

//output {168,99,98,88,68}
Share:

Reversing integer Array through LINQ in c#

public Int32[] ReverseThroughLINQ(Int32[] _inputs,int k=0)
 {
 if (k==0) {
  k=_inputs.Count();
 }
 int[] reverse = _inputs.Take(k).Reverse().ToArray();
 int[] straight = _inputs.Skip(k).ToArray();
 int[] _concatenatedString = reverse.Concat(straight).ToArray();
 return _concatenatedString;
 }
Share: