LINQ and conversion operators

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

No Comments