Here i need to get the last value from a model list in a view without looping it..Here is my controller code
public IList<ProductDetailModel> GetWPDetails()
{
ProductDetailModel Viewmodel;
string funname = "GetCSpecialWPDetails";
List<ProductDetailModel> getWPDetails = new List<ProductDetailModel>();
getWPDetails = objrest.EcommerceWPDetails(funname);
List<ProductDetailModel> WPDetails = new List<ProductDetailModel>();
foreach (var item in getWPDetails)
{
Viewmodel = new ProductDetailModel();
Viewmodel.Productid = item.Productid;
Viewmodel.ProductName = item.ProductName;
Viewmodel.CategoryID = item.CategoryID;
Viewmodel.ProductRate = item.ProductRate;
Viewmodel.DiscountRate = item.DiscountRate;
Viewmodel.imageurl1 = item.imageurl1;
WPDetails.Add(Viewmodel);
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT ThemeColor,LayoutDesign FROM dbo.Cpecial_Partner_Design WHERE [PartnerID]='" + Partid + "'", con);
con.Open();
using (SqlDataReader myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
Viewmodel = new ProductDetailModel();
Viewmodel.ThemeColor = myReader["ThemeColor"].ToString();
Viewmodel.LayoutDesign = myReader["LayoutDesign"].ToString();
WPDetails.Add(Viewmodel);
}
myReader.Close();
}
con.Close();
return WPDetails;
}
and here in view i am getting the values by looping the model and the total count is 47 but what i need is i need the 47th value alone that is the last value alone without any looping.
View code
@foreach (var item in Model)
{
@Html.EditorFor(modelItem => item.ThemeColor)
@Html.EditorFor(modelItem => item.LayoutDesign)
}
Any suggestion?
Use linq! In your case .Last() method.
Try: