0

谁能告诉我如何动态地用数据填充 Galaxy 类?

public class Galaxy
{
    public string Name {get; set;}
    public string Distance {get:set;}
}

而不是手动填充它:

var theGalaxies = new List<Galaxy>
{
    new Galaxy() {Name="Tadpole", Distance="200"},
    new Galaxy() {Name="Andromeda", Distance="300"}
};

我想动态填充它。但是,由于 for 循环,无法编译此代码:

var theGalaxies = new List<Galaxy>
{
    for (int i=0; i < someArray.Length; i++)
    {
       new Galaxy() {Name=someArray[0], distance=someArray[1]}
    } 
};


foreach (Galaxy theGalaxy in theGalaxies)
{
        Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.Distance);
}
4

5 回答 5

3
var theGalaxies = Enumerable.Range(0, 1000)
                            .Select(x => new Galaxy { Name = "Galaxy" + x.ToString(), Distance = x.ToString() })
                            .ToList();
于 2013-08-30T21:11:01.137 回答
1

不能在对象初始化器中使用循环,而是尝试如下:

var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i++)
      theGalaxies.Add(new Galaxy() {Name=someArray[0], distance=someArray[1]});
于 2013-08-30T21:09:44.120 回答
0

它看起来像 C#。

var theGalaxies = new List<Galaxy>():
Galaxy galxy;
for (int i = 0; i < someArray.Length; i++)
{
    galxy =new Galaxy() {Name = someArray[0], distance = someArray[1]};
    theGalaxies.Add(galxy);
};
于 2013-08-30T21:19:27.630 回答
0

假设someArray交替的星系名称和距离:

var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i+=2)
    theGalaxies.Add(new Galaxy() {Name=someArray[i], Distance=someArray[i+1]});

带参数的构造函数也不错:

public class Galaxy
{
    public Galaxy(string name, string distance)
    {
        Name = name;
        Distance = distance;
    }
    public string Name {get; set;}
    public string Distance {get:set;}
}

//...

var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i+=2)
    theGalaxies.Add(new Galaxy(someArray[i], someArray[i+1]));
于 2013-08-30T21:10:39.857 回答
0

for将您的循环代码更改为:

var theGalaxies = new List<Galaxy>();

for (int i=0; i < someArray.Length; i++)
{
    var temp = new Galaxy();
    temp.Name = someArray[0];
    temp.Distance = someArray[1];

    theGalaxies.Add(temp);
} 
于 2013-08-30T21:11:53.010 回答