Best method to use IDataReader as IEnumerable?

后端 未结 6 814
攒了一身酷
攒了一身酷 2021-02-06 13:16

I need to use Linq on any IDataReader implementations like this

var c = sqlDataReader.AsEnumerable().Count();

Example:

<
6条回答
  •  有刺的猬
    2021-02-06 13:56

    Here are my two cents :

    public static IEnumerable Enumerate(this T reader) where T: IDataReader 
    { 
       using(reader) 
          while(reader.Read()) 
             yield return reader; 
    } 
    
    public void Test()
    {
      var Res =
        from Dr in MyDataReader.Enumerate()
        select new {
          ID = (Guid)Dr["ID"],
          Description = Dr["Desc"] as string
        };
    }
    

    I felt the urge to post this, because it is very important to dispose a DataReader after use, and no answer mentioned it.

    That's why my implementation has a using statement around the while loop. In this way, I can do "one hand" queries whithout worrying about the DataReader disposal.

提交回复
热议问题