【问题标题】:property remove from the list属性从列表中删除
【发布时间】:2011-10-10 07:05:42
【问题描述】:

从列表中删除属性

        NorthwindDataContext db = new NorthwindDataContext();
        List<CategorySml> oList = new List<CategorySml>();
        oList = db.Categories.Select(p => new CategorySml { CategoryID = p.CategoryID, CategoryName = p.CategoryName }).ToList();

class CategorySml

{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

我的列表包含超过 100 行,现在我想从我的列表 oList 中删除 CategoryID 属性。我知道如何从以下语法中的列表中删除项目那个,但我不知道如何删除一个项目的属性

oList.RemoveAll(x => x.CategoryID== 1);

帮我从列表中删除属性。提前致谢。

【问题讨论】:

  • 你真的应该接受正确的答案

标签: c# linq linq-to-objects


【解决方案1】:

如果您想“删除”该属性,您将创建没有此属性的新类型:

oList = db.Categories.Select(p => new YourNewCategorySml { 
  CategoryName = p.CategoryName })
  .ToList();  

或使用匿名类型:

oList = db.Categories.Select(p => new { CategoryName = p.CategoryName })
  .ToList();  

【讨论】:

  • 谢谢,这是避免不需要的属性的好方法。谢谢
【解决方案2】:

继承呢?

class BaseCategory
{
  public string CategoryName { get; set; }
}
class CategorySml : BaseCategory

{
    public int CategoryID { get; set; }
}

NorthwindDataContext db = new NorthwindDataContext();
        List<BaseCategory> oList = new List<BaseCategory>();
        oList = db.Categories.Select(p => new BaseCategory{ CategoryName = p.CategoryName }).ToList();

【讨论】:

    【解决方案3】:

    你可以通过匿名类型变量来做到这一点

    try
                {
                   NorthwindDataContext db= new NorthwindDataContext();
                   var oList = db.Categories.Select(p => new { Categoryname = p.CategoryName }).ToList();                
                   dg.DataSource = oList;
    
    
    
                    MessageBox.Show("OK"); 
                }
                catch (Exception ex)
                {
    
                    MessageBox.Show(ex.Message);   
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-23
      • 2020-09-28
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多