LINQ and conversion operators

Posted by vik20000in on ASP.net Weblogs See other posts from ASP.net Weblogs or by vik20000in
Published on Thu, 15 Apr 2010 03:15:00 GMT Indexed on 2010/04/15 3:23 UTC
Read the original article Hit count: 543

Filed under:
|
|
|

LINQ has a habit of returning things as IEnumerable. But we have all been working with so many other format of lists like array ilist, dictionary etc that most of the time after having the result set we want to get them converted to one of our known format. For this reason LINQ has come up with helper method which can convert the result set in the desired format. Below is an example

var sortedDoubles =

        from d in doubles

        orderby d descending

        select d;

    var doublesArray = sortedDoubles.ToArray();

This way we can also transfer the data to IList and Dictionary objects.

Let’s say we have an array of Objects. The array contains all different types of data like double, int, null, string etc and we want only one type of data back then also we can use the helper function ofType. Below is an example

    object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 };

    var doubles = numbers.OfType<double>();

Vikram

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET