Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, November 15, 2011

Lambda Expressions with Multiple Parameters


Lambda Expressions are getting good recognition among developers and it would be nice to have the next level of information regarding it.

Summary

As you know, Lambda Expressions is an anonymous function that can contain expression or statements. The lambda expression uses the => (goes to) operator.

Example of One Parameter Lambda
var result = list.Where(i => i == 100);

Example of Two Parameter Lambda
var result = list.Where((i, ix) => i == ix);

Code Explained

In the above case the Where() method is having two overloads and we were using the second overloaded method which takes Func as argument.

Lamba1.gif

The first argument is the element itself and second would be the index. The value of index will be passed by the caller.

Applications of Index Parameters

It could be of rare applications where we needed the lambda index parameter. I have seen in many interviews they ask scenarios based on it. Some of the scenarios are given below.

Scenario 1
You have got a list of random integers. We need to find the numbers whose value equals to the index. How to achieve this in one line?

Setup Code

The following code can be used for creating the main list.
IList<int> list = new List<int>();
list.Add(0); // Value = Indexlist.Add(2);
list.Add(2); // Value = Indexlist.Add(1);
list.Add(4); // Value = Index

One Line Lambda Solution
var sublist = list.Where((i, ix) => i == ix);

The Lengthy Solution
var newList = new List<int>();
int jx = 0;
foreach (int j in list)
    if (jx++ == j) // Check index and increment index        newList.Add(j);

From the above code we can see without lambda expressions the solution will be taking more than 1 lines.

Result

We can see the associated result of the console application. The source code is attached with the article.

Lamba2.gif

DateTime in C#


In this article we perform various operations on dates and times using DateTime. A DateTime structure represents dates and times. We use DateTime to work with dates, times, and both. The DateTime type in the C# language provides useful methods and properties for computing these values. DateTime represents a date and time of the day.  For example there are methods to find important days, such as yesterday, tomorrow, the first of the year, and the last day.
1. To find today's date
Console.WriteLine("Today: {0}"DateTime.Today);
Console.WriteLine("Today: {0}"DateTime.Now);
Difference between Today and Now property
Today - This displays today's date. The time value is 12:00:00.
Now - This displays the current date and time of the system, expressed as the local time. In other words the Now property returns a DateTime object that has the date and time values for right now.
2.  To find yesterday's date
class Program
    {
        static DateTime Yesterdaydate()
        {
            return DateTime.Today.AddDays(-1);
        }

        static void Main(string[] args)
        {
            DateTime yes = Yesterdaydate();
            Console.WriteLine("Yesterday was: {0}", yes);
        }
    }

3. To find tomorrow's date

class Program
    {
        static DateTime Yesterdaydate()
        {
            return DateTime.Today.AddDays(1);
        }

static void Main(string[] args)

        {      
           DateTime d = Tomorrowdate();
           Console.WriteLine("Tomorrow date was: {0}", d);
        }
4.  To find the First day in a year
class Program
    {
        static DateTime FirstDayOfYear()
        {
            return FirstDayOfYear(DateTime.Today);
        }
        static DateTime FirstDayOfYear(DateTime y)
        {
            return new DateTime(y.Year, 1, 1);
        }
        static void Main(string[] args)
        {
          DateTime m = new DateTime(1999, 6, 1);
           Console.WriteLine("First day of 1999: {0}",
           FirstDayOfYear(m));
        }
 
5. Adding DateTime values
DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");
           TimeSpan addduration = TimeSpan.Parse("1.01:01:01");
           theDate = theDate.Add(addduration);
6.  Subtracting DateTime values
DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");
           TimeSpan addduration = TimeSpan.Parse("1.01:01:01");
           theDate = theDate.Subtract(addduration);
           Console.WriteLine("abstract date is: {0}", theDate);
 
Other DateTime Properties
7. DayOfWeek
DayOfWeek property returns the name of the day in a week.
DateTime findwyd = new DateTime(2011, 6, 21, 7, 10, 24);
Console.WriteLine("Day of Week:{0}", findwyd.DayOfWeek);
Console.WriteLine("Day of Year: {0}", findwyd.DayOfYear);
Console.WriteLine("Time of Day:{0}", findwyd.TimeOfDay);
8. DayOfYear
The DayOfYear property returns the day of a year.
DateTime findwyd = new DateTime(2011, 6, 21, 7, 10, 24);
Console.WriteLine("Day of Year: {0}", findwyd.DayOfYear);
TimeOfDay
The TimeOfDay property returns the time element from a DateTime.
DateTime findwyd = new DateTime(2011, 6, 21, 7, 10, 24);
Console.WriteLine("Time of Day:{0}", findwyd.TimeOfDay);
For Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace datetime_function
{
    class Program
    {
        static DateTime Yesterdaydate()
        {
            return DateTime.Today.AddDays(-1);
        }

        static DateTime Tomorrowdate()
        {
            return DateTime.Today.AddDays(1);
        }
        static DateTime FirstDayOfYear()
        {
            return FirstDayOfYear(DateTime.Today);
        }
        static DateTime FirstDayOfYear(DateTime y)
        {
            return new DateTime(y.Year, 1, 1);
        }
        static void Main(string[] args)

        {
            DateTime findwyd = new DateTime(2011, 6, 21, 7, 10, 24);
            Console.WriteLine("Today: {0}"DateTime.Today);
            Console.WriteLine("Today: {0}"DateTime.Now);
           DateTime yes = Yesterdaydate();
           Console.WriteLine("Yesterday was: {0}", yes);
           DateTime d = Tomorrowdate();
           Console.WriteLine("Tomorrow date was: {0}", d);
           DateTime m = new DateTime(1999, 6, 1);
           Console.WriteLine("First day of 1999: {0}",
           FirstDayOfYear(m));
           DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");
           TimeSpan addduration = TimeSpan.Parse("1.01:01:01");
           theDate = theDate.Add(addduration);
           Console.WriteLine("add date is: {0}",theDate);
           theDate = theDate.Subtract(addduration);
           Console.WriteLine("abstract date is: {0}", theDate);
           Console.WriteLine("Day of Week:{0}", findwyd.DayOfWeek);
           Console.WriteLine("Day of Year: {0}", findwyd.DayOfYear);
           Console.WriteLine("Time of Day:{0}", findwyd.TimeOfDay);
        }
    }
}
OUTPUT
datetime2.gif