我有这样的课

public class Sample
{
    public string A { get; set; }
    public int B { get; set; }
}

var sampleValues = new List<Sample>(){
        new Sample(){ A = "a1", B = 1 },
        new Sample(){ A = "a2", B = 2 },
        new Sample(){ A = "a3", B = 3 },
        new Sample(){ A = "a4", B = 4 },
        .....
        new Sample(){ A ="a30", B = 30}
    };

有没有什么简单的方法可以用 30 个连续的值来初始化它,如图所示?

最佳答案

使用 Enumerable.Range 像:

List<Sample> samvalues = Enumerable.Range(1, 30)
                               .Select(r => new Sample {A = "a" + r, B = r})
                               .ToList();

或者
List<Sample> samvalues = Enumerable.Range(1, 30)
                    .Select(r => new Sample {A = String.Format("{0}{1}", "a", r), B = r})
                    .ToList();

关于c# - 如何使用连续值初始化列表<type>?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25978197/

10-14 03:47