DataReader AsEnumerable (LINQ) with fields name


SUBMITTED BY: Guest

DATE: Nov. 11, 2013, 9 p.m.

FORMAT: Text only

SIZE: 1.2 kB

HITS: 934

  1. // create a static class
  2. public static class DataReaderExtension
  3. {
  4. public static IEnumerable<Dictionary<string, object>> AsEnumerable(this System.Data.IDataReader source)
  5. {
  6. if (source == null)
  7. throw new ArgumentNullException("source");
  8. while (source.Read())
  9. {
  10. Dictionary<string, object> row = new Dictionary<string, object>();
  11. for (int i = 0; i < source.FieldCount; i++)
  12. {
  13. object value = source.GetValue(i);
  14. // return an empty string for dbnull value of field type string
  15. if (source.GetFieldType(i) == typeof(string) && source.IsDBNull(i))
  16. value = string.Empty;
  17. row.Add(source.GetName(i), value);
  18. }
  19. yield return row;
  20. }
  21. }
  22. }
  23. // suppose you have a class named MYBooks with properties names ID (int) and TITLE (string)
  24. // and the datareader contains more records with two fileds named ID_BOOK and TITLE
  25. myDataReader.AsEnumerable().Select(i => new MYBooks()
  26. {
  27. ID = (int)i["ID_BOOK"],
  28. TITLE = (string)i["TITLE"]
  29. });

comments powered by Disqus