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

Wednesday, May 18, 2011

Order by with out Culture

If you want to do some operations without any culture you can do with the help of StringCompare.Ordinal or StringCompare.OrdinalIgnoreCase.

void Main()
{
string[] nonCulture = { "äax", "ääü", "äbü" };

IEnumerable orderNonCulture = nonCulture.OrderBy( r => r, StringComparer.Ordinal);

orderNonCulture.Dump();
}

Monday, May 16, 2011

Sunday, May 15, 2011

?? Operator used in Linq

Here is the Msdn link for ?? Operator

if need to order by a query which need to orderby column1 if not null, if null orderby column2

void Main()
{

List orderList= new List()
{
new Order(1, 4),
new Order(null,6),
new Order(2,5),
new Order(null,3),
};

var k = from p in
orderList
orderby p.ID ?? p.Count
select p;
}


class Order
{
public int? ID{get;set;}
public int? Count{get;set;}


public Order(int? id,int? count)
{
ID =id;
Count =count;
}
}

Tuesday, May 10, 2011

what is the use of parms keyword in C#

here is the msdn link for Linkparams

E.g:

with params

void Main()
{
Method(1,2,3); // you can call it like this
}

static void Method(params int[] array)
{
for(int i=0;i < array.Length;i++)
{
Console.WriteLine(array[i]);
}
}


without params

void Main()
{

Method(1,2,3); // throws error
}

static void Method (int[] array)
{
for(int i=0;i < array.Length;i++)
{
Console.WriteLine(array[i]);
}
}

you have to do

void Main()
{
int[] i = {1,2,3};
Method(i);
}

static void Method (int[] array)
{
for(int i=0;i < array.Length;i++)
{
Console.WriteLine(array[i]);
}
}

why the entry point of C# should be static void Main()

here is a couple of links which says the answer properly

Msdn: http://msdn.microsoft.com/en-us/library/acy3edy3.aspx
SO:http://stackoverflow.com/questions/5954439/c-entry-point-function

why the method name should be Main()

The using System; directive references a namespace called System that is provided by the Common
Language Infrastructure (CLI) class library. This namespace contains the Console class referred to in
the Main method.

taken from ecma-international

Monday, May 9, 2011

yield vs return in C#

The yield keyword signals to the compiler that the method in which it appears is an iterator block.

  • yield can be used to return partially.
  • yield maintains the state of the object
Simple example

void Main()
{
foreach(int i in GetDivideByTwo())
{
Console.WriteLine(i);
}
}


static System.Collections.Generic.IEnumerable GetDivideByTwo()
{
for (int i = 0; i < 100; i++)
yield return i/2;
}


Here is couple of good links

http://stackoverflow.com/questions/410026/c-proper-use-of-yield-return

http://stackoverflow.com/questions/1088442/what-is-the-purpose-advantage-of-using-yield-return-iterators-in-c/1088452#1088452

http://stackoverflow.com/questions/3969963/when-not-to-use-yield-return/3970171#3970171