Let’s look at this code:
IList<IHouseAnnouncement> list = new List<IHouseAnnouncement>();
var table = adapter.GetData(); //get data from repository object -> DataTable
if (table.Rows.Count >= 1)
{
for (int i = 0; i < table.Rows.Count; i++)
{
var anno = new HouseAnnouncement();
anno.Area = float.Parse(table.Rows[i][table.areaColumn].ToString());
anno.City = table.Rows[i][table.cityColumn].ToString();
list.Add(anno);
}
}
return list;
Is it better way to write this in less code and better fashion (must be 🙂 )? Maybe using lambda (but let me know how)?
Thanks in advance!
Just FYI, you’re never adding the new
HouseAnnouncementto your list, and your loop will never execute for the last row, but I’m assuming those are errors in the example rather than in your actual code.You could do something like this:
I usually go for readability over brevity, but I feel like this is pretty readable.
Note that while you could still cache the
DataTableand usetable.powierzchniaColumnin the lambda, I eliminated that so that you didn’t use a closure that wasn’t really necessary (closures introduce substantial complexity to the internal implementation of the lambda, so I avoid them if possible).If it’s important to you to keep the column references as they are, then you can do it like this:
This will add complexity to the actual IL that the compiler generates, but should do the trick for you.