Linq - Data reader - selecting more than one value

I came across a situation to bind gridview with selecting data from datareader using linq
I used following code.




public void ShowAthletes()
{
cn.Open();
SqlCommand cmd = new SqlCommand("SpName", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("SubscriptionId", Parameter1);
cmd.Parameters.AddWithValue("EMail", "parametername");
SqlDataReader dr=cmd.ExecuteReader();

---------Linq part of query starts-----------------------------
grd.DataSource = from t in dr.DataRecord()// note data reader does implement IEnumberable Sowe need to extend it
where t[4].ToString() == "XXXXXX" // some specific email id
orderby t[2].ToString()
select new {Email = t[4].ToString(), FirstName = t[2].ToString() };


----------------Linq part query ends here--------------------------
grd.DataBind();
dr.Close();
cn.Close();
cmd.Dispose();
}

To implement Ienumerable for data reader


public static class DataReaderExtension
{
public static IEnumerable DataRecord(this System.Data.IDataReader source)
{
if (source == null)
throw new ArgumentNullException("source");
while (source.Read())
{
Object[] row = new Object[source.FieldCount];
source.GetValues(row);
yield return row;
}
}
}

Popular Posts