This can be done using Select
and ToList
:
var lstProductData = dtReport.Rows.Cast<DataRow>()
.Select(row => new ProductData(new Guid(row["ProductID"].ToString())
, row["Product"].ToString()))
.ToList();
Question
Sample Class:
public class ProductData
{
private Guid ProductID { get; set; }
private string ProductDescription { get; set; }
public ProductData(Guid pID, string pDescription)
{
this.ProductID = pID;
this.ProductDescription = pDescription;
}
}
Create a list of ProductData:
private static List<ProductData> GetProductDataList()
{
// code to populate DataSet ds here
DataTable dtReport = ds.Tables[0];
List<AssetData> lstProductData = new List<ProductData>();
int index = 1;
foreach (DataRow row in dtReport.Rows)
{
lstProductData.Add(new ProductData(new Guid(row["ProductID"].ToString()), row["Product"].ToString()));
index++;
}
return lstProductData.ToList();
}
Code works perfectly fine and as expected. But, I think the foreach loop can be avoided using LINQ. I try to utilize LINQ as much as possible for various reasons (cleaner looking code is one of the reason - correct me if I am wrong).
Is there any way I can achieve the same thing as above using LINQ and with minimum code.
Solution
This can be done using Select
and ToList
:
var lstProductData = dtReport.Rows.Cast<DataRow>()
.Select(row => new ProductData(new Guid(row["ProductID"].ToString())
, row["Product"].ToString()))
.ToList();