簡體   English   中英

使用什么樣的數據結構?

[英]What kind of data structure to use?

我正在開展一個需要跟蹤的項目:

  • 5-6只是字符串名稱的根項
  • 每個根項都需要具有不同標識符類型的多個子項(int,string,float等)。 一個根的所有子節點都是相同類型,但每個根節點將具有不同的子類型
  • 用戶需要能夠從每個根添加/刪除子項
  • 我稍后需要單獨訪問每個孩子,並在需要時執行字符串操作和解析

我想過可能會使用一個字典,其中Key是一個字符串,而Values是對象列表。 或者為每個根項創建一個唯一的類,每個類將包含一個子列表。

有沒有人有什么好建議? 我對OOP還很新,請耐心等我:)

謝謝!

public interface IRoot {}

public class RootItem<T> : IRoot
{
    public string Name { get; set; }
    public List<T> Children {get; set; }
}

然后保持一個Dictionary<string, IRoot>來保存它們。

Dictionary<string, IRoot> hair = new Dictionary<string, IRoot>();
hair.Add(
  new RootItem<int>()
      {
        Name = "None",
        Children = new List<int>() {1, 2, 3, 4}
      }
);

hair.Add(
  new RootItem<decimal>()
      {
        Name = "None",
        Children = new List<decimal>() {1m, 2m, 3m, 4m}
      }
);

如何使用List<T>包含子類的泛型類:

public class Root<T>
{
    private List<T> children = null;

    public Root(string name)
    {
        Name = name;
    }

    public string Name { get; set; }

    public List<T> Children
    {
        get
        {
            if (children == null)
            {
                children = new List<T>();
            }

            return children;
        }
    }
}

Root<int> intRoot = new Root<int>("IntRoot");
intRoot.Children.Add(23);
intRoot.Children.Add(42);

Root<string> stringRoot = new Root<string>("StringRoot");
stringRoot.Children.Add("String1");
stringRoot.Children.Add("String2");
stringRoot.Children.Add("String3");
stringRoot.Children.Add("String4");

如果你想在一個對象中保存所有的根,你可以編寫自己的類或使用一個Tuple

var rootGroup = Tuple.Create(intRoot, stringRoot);
// intRoot is accessible as rootGroup.Item1
// stringRoot is accessible as rootGroup.Item2

聽起來像Dictionary<string, Tuple<type1, type 2, etc>>是一個很好的候選者。

鍵是字符串(root)。 根的孩子是元組。 我們可以添加項目到元組。 感謝您指出了這一點。

元組的好起點

這是一種方法。 需要進行大量的投射,但它完成了工作:

    static void Main(string[] args)
    {
        Dictionary<string, IRootCollection> values = new Dictionary<string, IRootCollection>();

        values["strings"] = new RootCollection<string>();
        (values["strings"] as RootCollection<string>).Add("foo");
        (values["strings"] as RootCollection<string>).Add("bar");

        values["ints"] = new RootCollection<int>();
        (values["ints"] as RootCollection<int>).Add(45);
        (values["ints"] as RootCollection<int>).Add(86);
    }

    interface IRootCollection { }
    class RootCollection<T> : List<T>, IRootCollection { }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM