Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C#
Tip/Trick

Simple IDataReader Extension Method

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
11 Feb 2014CPOL2 min read 15.1K   6   2
A simple, but powerful way to convert an IDataReader to an IEnumerable

Introduction

One of the best features of the .NET framework is its ability to define custom extension methods. This tip will demonstrate a very simple extension method that allows converting an IDataReader into an IEnumerable which then allows querying using LINQ, either through extension methods or the LINQ DSL in C# or VB.NET.

The Extension Method

The extension method is very simple and is as follows:

C#
public IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)
{
  while(reader.Read())
    yield return reader;
}  

This method is quite simplistic, and yet provides an abundance of features. It leverages C#'s ability to create an enumerable based on the yield return statement and provides the ability to leverage LINQ for various types of queries.

Examples

Using the extension method is equally simple, but powerful.

Example 1 - Convert Reader to an IEnumerable<T>

Let's say, for example, that we want to convert the IDataReader into Person objects.

C#
//Converts reader to person list
public List<Person> GetPersonsFromReader(IDataReader reader)
{
  return reader
    .AsEnumerable()
    .Select(r => new Person { FirstName = (string)r["FirstName"], 
    	LastName = (string)r["LastName"] })
    .ToList();
}   

Notice how simple it is now to covert an IDataReader into an IEnumerable<T> and transform that IDataReader into a meaningful data type. 

Example 2 - Deciding What Data To Return

It's possible that every row from an IDataReader is not what we want. Since we can now convert an IDataReader into a queryable form, we can now exclude rows that do not match the criteria for which we are looking and only include those that do match.

C#
public List<Widget> FindWidgets(IDataReader reader)
{
  return reader
    .AsEnumerable()
    .Where(record => (int)record[0] != 10)
    .Select(record => new Widget { V1 = (int)record[0], 
           V2 = (string)record[1], V3 = (string)record[2] })
    .ToList();
}

Conclusion

I hope this article has been helpful and will be useful. As you can see, it's quite easy to allow any IDataReader, including those of your own making, to be converted into something you can query with all the power of LINQ.

These examples are contrived and may not be proper for your programming project in that I used magic numbers and other programming faux pas that you might want to avoid. However, the extension method itself is quite useful and a welcome addition to any programmer's toolbox or bag of tricks.

I would appreciate any feedback you might have on this tip.

Points of Interest

For more information and details on extension methods, visit MSDN.

If you need more help with the yield return statement, you can also visit the MSDN page on it.

History

  • Version 1.0
  • Version 1.1 - Changed Enumerable<T> to IEnumerable<T>. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I am a software engineer, developer, programmer with 20+ years of experience working on various types of systems and design and have built a lot of software from the ground up and maintained a lot of software developed by others.

I truly enjoy working in this field and I'm glad I started this career more than 20 years ago.

I've learned, over the years, that the biggest and toughest bugs to find usually have the simplest solution once found.

Comments and Discussions

 
QuestionFine! Pin
Volynsky Alex12-Feb-14 0:26
professionalVolynsky Alex12-Feb-14 0:26 
QuestionI know your code is smaller... Pin
Paulo Zemek11-Feb-14 4:15
mvaPaulo Zemek11-Feb-14 4:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.