开发者

How can I better populate two arrays in a class?

I need to populate a class of SubTopics that looks like this:

public class SubTopic
{
    public int[] SubTopicId { get; set; }
    public string[] Description { get; set; }
}

So far I have the following code to insert in the description but not yet the SubTopicId.

var description = new List<string>();
description.Add("afds).");
description.Add("afas.");
...
...
description.Add("aees.");

new SubTopic { Description  =  description.ToArray()}

Can anyone think of a simple way for me to populate the SubTopicId with numbers 1,2,3 .. etc and also is there开发者_高级运维 maybe a better way that I can populate the SubTopic class. Something better than adding to a list and then converting to an array?


var description = new[]{"afds).", "afas.", /*...,*/ "aees."};
var subTopic = new SubTopic { 
    Description  =  description,
    SubTopicId = Enumerable.Range(1, description.Length).ToArray()
};


You could use class and array initializers:

var subTopic = new SubTopic
{
    SubTopicId = new[] { 1, 2, 3 },
    Description = new[] { "afds).", "afas.", "aees." }
};


You can do it all inline if you want:

var x = new SubTopic {
  Description = new string[] { "a", "b" },
  SubTopicId = new int[] { 1, 2, 3 }
};


for (int i = 0; i < SubTopicId.Length; i++)
{
    SubTopicId[i] = i;
}

As for the strings array, as has been suggested, you can do it inline.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜