在C#中创建扩展的键引用数组?

时间:2015-01-12 00:46:45

标签: c# arrays

我有一个我想要创建的对象类型:

private LeagueItem[] leagues;

public class LeagueItem
{
    public string name { get; set; }
    public string tier { get; set; }
    public string points { get; set; }
    public bool fresh { get; set; }
    public bool streak { get; set; }
}

然后我希望能够在我的程序迭代时向这个数组中添加项目:

foreach (var league in results.Children())
{
    leagues[league.id] = new LeagueItem()
    {
        name = league.name,
        tier = league.tier + " " + league.entries[0].division,
        points = league.entries[0].leaguePoints,
        fresh = league.entries[0].isFreshBlood,
        streak = league.entries[0].isHotStreak,
    };
}

您会注意到我希望数组具有从每个联盟的ID分配的键索引。这是因为我需要根据这些ID访问联盟数据,例如leagues[###].name

我遇到的问题是这不起作用。数组需要您在初始化时设置大小。我不会提前知道数组的大小,联盟的ID可以是各种各样的字符。什么是完成我想要做的最好和最简单的方法?

3 个答案:

答案 0 :(得分:4)

使用字典,这使得数组基于索引,并且可以使用更多项扩展字典。字典的关键字代表你的联盟标识符,值是你的联盟对象。尝试这样的事情:

// declare the league dictionary
private IDictionary<int, LeagueItem> leagues; // assuming the league ID is a number

// define the league dictionary
leagues = new Dictionary<int, LeagueItem>();

// add new leagues
foreach (var league in results.Children())
{
    leagues.Add(
        league.id,
        new new LeagueItem()
        {
            name = league.name,
            tier = league.tier + " " + league.entries[0].division,
            points = league.entries[0].leaguePoints,
            fresh = league.entries[0].isFreshBlood,
            streak = league.entries[0].isHotStreak,
        });
}

答案 1 :(得分:0)

您正在寻找Dictionary<int, T>

答案 2 :(得分:0)

我会为您指定的场景使用列表。

List<LeagueItem> leagues = new List<LeagueItem>();

foreach (var league in results.Children())
{
    leagues.Add(new LeagueItem()
    {
        name = league.name,
        tier = league.tier + " " + league.entries[0].division,
        points = league.entries[0].leaguePoints,
        fresh = league.entries[0].isFreshBlood,
        streak = league.entries[0].isHotStreak,
    });
}

要根据id查找联赛项目,我会使用Linq:

var league = leagues.SingleOrDefault(x => x.id == 10);

你甚至可以用Linq语句替换for循环。