繁体   English   中英

如何将指定数量的列表元素添加到 ILIST?

[英]How can I add a specified number of list elements to an ILIST?

我有一个 class 如下:

public class ABC {
 public IList<TextFillerDetail> TextFillerDetails        
 { get { return _textfillerDetails; } }        
private List<TextFiller> _textfillerDetails = new List<TextFiller>();
}

我实例化这个 class 并向它添加一些 TextDetails:

var ans = new ABC();
ans.TextDetails.Add(new TextDetail());
ans.TextDetails.Add(new TextDetail());
ans.TextDetails.Add(new TextDetail());
ans.TextDetails.Add(new TextDetail());

有没有一种方法可以通过向 class 添加一些代码(例如另一种构造函数)来一步完成。 例如,通过传入一个数字 5 来请求添加五个元素?

var ans = new ABC(5);

您可以将其添加为构造函数参数:

public class ABC()
{
    public ABC(int count)
    {
        for (int i = 0; i < count; i++) 
        {
            TextDetails.Add(new TextDetail());
        }
    }

    // Stuff
}

当然,您可以使用将初始化列表的构造函数:

public class ABC 
{
    public ABC(int count)
    {
       if (count < 1) 
       {
           throw new ArgumentException("count must be a positive number", "count");
       }
        _textfillerDetails = Enumerable
            .Range(1, count)
            .Select(x => new TextDetail())
            .ToList();
    }

    public IList<TextFillerDetail> TextFillerDetails { get { return _textfillerDetails; } }        
    private List<TextFiller> _textfillerDetails;
}

当然:

public class ABC {
 public IList<TextFillerDetail> TextFillerDetails        
 { get { return _textfillerDetails; } }        
  public ABC(int capacity)
  {
    _textfillerDetails = new List<TextFiller>(capacity);
  }
private List<TextFiller> _textfillerDetails;
}

有几种方法:

使用初始化器; 它节省了一点打字:

var ans = new ABC{
    new TextDetail(),
    new TextDetail(),
    new TextDetail(),
    new TextDetail(),
    new TextDetail(),
}

更好的主意:使用 Linq 重复初始化 lambda:

var ans = Enumerable.Repeat(0,5).Select(x=>new TextDetail()).ToList();

您可以放入一个重载的构造函数,它将要添加的项目数作为参数。

但是为什么你需要这样做呢? 您不能根据需要将TextDetail对象添加到列表中吗?

只是为了这个任务,是的,

private List<TextFiller> _textfillerDetails = new List<TextFiller>();
public ABC(int capacity)
  {
     for(int index  = 0; index < capacity; index ++)
       _textfillerDetails.Add(new TextDetail());
  }

您可以使用 for 循环或 linq:

public class ABC
{
    public IList<TextFillerDetail> TextFillerDetails { get; private set }

    public ABC() : this(0)
    {
    }

    public ABC(int count)
    {
        TextFIllerDetails = Enumerable.Range(0,count)
                                      .Select(x => new TextFillerDetail())
                                      .ToList();
    }
}

也考虑使用,

IEnumerable 或 ICollection 或 IQueryable 对象。

雷·阿肯森

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM