Question

.
.
List<DailyEntry> entries = null;
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
    entries = rdr.Select(r => new DailyEntry
    {
        ID = int.Parse(r["Col_ID"].ToString()),
        Amount = decimal.Parse(r["Col_Amount"].ToString()),
        Date = DateTime.Parse(r["Col_Date"].ToString()),
        Remarks = r["Col_Remarks"].ToString()
    }).ToList();
}
.
.

extrension method select is

 public static IEnumerable<T> Select<T>(this SqlCeDataReader reader,
                                        Func<SqlCeDataReader, T> projection)
 {
     while (reader.Read())
     {
         yield return projection(reader);
     }
 }

where DailyEntry class is

class DailyEntry
{
    public int ID { get; set; }
    public DateTime Date { get;set; }
    public Site Site { get; set; }
    public decimal Amount { get; set; }
    public string Remarks { get; set; }
}

DailyEntry class has one more property of type Site

class Site
{
    public int SiteID { get; set; }
    public string SiteName { get; set; }
}

Now I want to initialize the Site property of DailyEntry just how all other properties are set in first code snippet..

I am not finding the way?

Was it helpful?

Solution

Unless I didn't understand the question, the answer is:

List<DailyEntry> entries = null;
using (SqlCeDataReader rdr = cmd.ExecuteReader())
{
    entries = rdr.Select(r => new DailyEntry
    {
        ID = int.Parse(r["Col_ID"].ToString()),
        Amount = decimal.Parse(r["Col_Amount"].ToString()),
        Date = DateTime.Parse(r["Col_Date"].ToString()),
        Remarks = r["Col_Remarks"].ToString(),
        Site = new Site 
        {
            SiteID = int.Parse(r["Site_ID"].ToString()),
            SiteName = r["name"].ToString()
        }
    }).ToList();
}

OTHER TIPS

Why not use the existing func? Something like this:

entries = rdr.Select(r => new DailyEntry
    {
        ID = int.Parse(r["Col_ID"].ToString()),
        Amount = decimal.Parse(r["Col_Amount"].ToString()),
        Date = DateTime.Parse(r["Col_Date"].ToString()),
        Remarks = r["Col_Remarks"].ToString(),
        Site = new Site {SideID = r["..."], SiteName = r["..."]}
    }).ToList();

All you have to do is create it inline the same way you are creating your new DailyEntry instance:

rdr.Select(r => new DailyEntry
{
    ID = int.Parse(r["Col_ID"].ToString()),
    Amount = decimal.Parse(r["Col_Amount"].ToString()),
    Date = DateTime.Parse(r["Col_Date"].ToString()),
    Remarks = r["Col_Remarks"].ToString(),
    Site = new Site 
           {
               SiteID = int.Parse(r["Site_ID"].ToString()),
               SiteName = r["Site_Name"].ToString()
           }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top