我想问一下将数据存储到列表中但不是所有这样的数据, 类别:
public class CategoryEnt
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int ParentID { get; set; }
public bool IsDisplayed { get; set; }
public bool IsTopCat { get; set; }
public bool IsTrending { get; set; }
public int SequenceID { get; set; }
public string Filtering { get; set; }
public string ImageURL { get; set; }
}
我只想添加到列表CategoryID,CategoryName,ImageUrl
while (reader.Read())
{
CategoryEnt category = new CategoryEnt();
category.CategoryID = Convert.ToInt32(reader["CategoryID"]);
category.CategoryName = reader["CategoryName"].ToString();
category.ImageURL = reader["ImageURL"].ToString();
list.Add(category);
}
现在,其余数据包括但是使用默认/空值,我不希望其余数据包括列表。如何将特定数据存储到列表中?任何线索?
答案 0 :(得分:0)
您无法直接执行此操作,但可以通过使用以下代码间接实现此目的:
List<CategoryEnt> CategoryEntList = new List<CategoryEnt>();
while (reader.Read())
{
CategoryEntList.Add(new CategoryEnt(){
CategoryID = Convert.ToInt32(reader["CategoryID"]),
CategoryName = reader["CategoryName"].ToString(),
ImageURL = reader["ImageURL"].ToString(),
});
}
var requiredValues = CategoryEntList.Select(x => new
{ CategoryID = x.CategoryID,
CategoryName = x.CategoryName,
ImageURL = x.ImageURL
}).ToList();
现在requiredValues
是一个列表,它只包含您在Select
中指定的那些值。您可以继续执行该操作;
答案 1 :(得分:0)
尝试只提供所需信息的课程。类似的东西:
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string ImageURL { get; set; }
}
然后您可以使用
创建原始班级public class CategoryEnt
{
public Category CategoryPrimaryDetails { get; set; }
public int ParentID { get; set; }
public bool IsDisplayed { get; set; }
public bool IsTopCat { get; set; }
public bool IsTrending { get; set; }
public int SequenceID { get; set; }
public string Filtering { get; set; }
}
您的原始代码变为:
List<Category> list = new List<Category>();
while (reader.Read())
{
Category category = new Category() {
CategoryID = Convert.ToInt32(reader["CategoryID"]);
CategoryName = reader["CategoryName"].ToString();
ImageURL = reader["ImageURL"].ToString()
}
list.Add(category);
CategoryEnt detailedCategory = new CategoryEnt() {CategoryPrimaryDetails = category};
}