Sunday, July 22, 2012

C# - Convert String to DateTime using ParseExact() method of DateTime

It is a common requirement to convert a Date/Time you have as a string to .NET native DateTime type.
The point to note here is to convey to the .NET Framework regarding the Date Format you provide as the input string. ParseExact() method of DateTime Type comes handy here.
Below is the solution to these

Convert String to DateTime in C# .NET
// String to DateTime
String dateText;
dateText = "1999-09-01 21:34 PM"; // Provide this according to your computer personal settings

DateTime myDate;
myDate = new DateTime();
myDate = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

Convert DateTime to String in C# .NET
//DateTime to String
myDate = new DateTime(1999, 09, 01, 21, 34, 00);
String dateText = myDate.ToString("yyyy-MM-dd HH:mm tt");

Tuesday, July 10, 2012

C# - Linq - Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int'

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'

In Linq queries sometimes you get the exception "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'". A scenario where you find this exception is as illustrated below:

int domainId = from p in pages
               where p.Value.aspxFile == pageFileName
               select p.Value.domain;

Logically I know there will only be one value being returned from this Linq Query statement, so it should work for me. But by syntax, this Linq statement returns type IEnumerable Collection.


int domainId = (from p in pages
        where p.Value.aspxFile == pageFileName
        select p.Value.domain).First();

This solves my issue and it will return only one object and not a collection. The object type is determined by the compiler at compile time which will be int in my case.

You can use .First() or FirstOrDefault() or Single(). But for Single() make sure that there is exactly only one element in the list.