【问题标题】:Information Storage for 3 variables3个变量的信息存储
【发布时间】:2015-05-03 14:37:40
【问题描述】:

我正在尝试创建一种在 C# 编程中存储 3 个变量、两个 int 和一个 point 的好方法。

我想到了一个使用字典数组的方法

 Dictionary<int, Point>[] ItemList = new Dictionary<int, Point>[4];

想法是一个变量必须在 1 到 4 之间,所以我会将它作为排序点或每个数组位置。第二个 int 必须介于 0 和 15 之间,并且该点位于 4x4 网格上。我认为这种方法会起作用,除了你在字典中不能有相同的键,而且由于两个整数都会重复,我不能把它们换掉。这个想法也落空了,同样的问题

Dictionary<int, int>[,] ItemList = new Dictionary<int, int>[4,4];

我也想过使用元组,但我没有太多(任何)经验,我对它们的实验也不太顺利。它的问题是我无法计算其中有多少物品。我是这样设置的。

Tuple<int, Point>[] ItemList = new Tuple<int, Point>[4];

和我的第一个例子一样,只是没有这样的代码

ItemList[1].Count    /*OR*/     ItemList[1].Length

如果我遗漏了一些非常明显的元组,请告诉我,或者建议一种不同的存储方法,将所有 3 个变量全部存储在一起。

【问题讨论】:

    标签: c# dictionary tuples


    【解决方案1】:

    您可以使用Tuple 直接存储这3 个数据结构。 Tuple 可以有两个以上的项目,并且可以是任何类型。这样,您就不必使用您的数组:

    Tuple<int, int, Point>
    

    要获取值,请使用相应的Item 属性。对于第一个 int,它将是 yourTuple.Item1。对于第二个 yourTuple.Item2 和 Point yourTuple.Item3

    如果您有多个Tuples,您可以使用经典的List 将它们全部存储:

    var tuples = new List<Tuple<int, int, Point>>();
    

    由于是列表,所以可以轻松获取计数:tuples.Count()

    【讨论】:

    • 我认为我仍然需要数组来达到我的目的,因为我只需要检查具有特定值的整数,而数组是一种简单的方法,但这是一个很好的方法主意。我会用这个尝试一些东西。
    • 列表是IEnumerable,因此您可以使用 LINQ 查询。例如,如果您只需要以 2 作为第一个 int 的元组,请使用 Where 查询,例如 tuples.Where(t =&gt; t.Item1 == 2)
    【解决方案2】:

    所以class 对我来说似乎是正确的结构。

    public class Something {
    
        public int Item1 { get; set; }
        public int Item2 { get; set; }
        public Point Location { get; set; }
    }
    

    然后将这些对象存储在List&lt;&gt;

    var List<Something> list = new List<Something>();
    

    将项目添加到列表中...

    list.Add(new Something() {Item1 = 4, Item2 = 8, Point = new Point(x,y)});
    

    然后使用一些 LINQ 来获得你想要的。

    var onlyItem1IsFour = (from item in list where 4 == item.Item1 select item).ToList();
    

    请原谅我的 LINQ。我习惯了 VB,可能大小写/语法略有错误

    【讨论】:

      【解决方案3】:

      好吧,使用列表的想法,我解决了我的问题。它有点混合了建议的想法和我使用数组的原始想法。如果您想做类似的事情,您不必使用数组,您可以使用具有 3 个值的元组,我只需要一个用于一个 int 值的数组,因为我需要根据那个 int 单独存储它们值为(介于 0 和 4 之间)。下面是一些可行的代码。

              List<Tuple<int, Point>>[] ItemList = new List<Tuple<int, Point>>[4]; // how to declare it
      
              for (int i = 0; i < 4; i++)
              {
                  ItemList[i] = new List<Tuple<int, Point>>(); // initilize each list
              }
      
              ItemList[1].Add(new Tuple<int, Point>(5, new Point(1, 2))); // add a new tuple to a specific array level
      
              int count = ItemList[1].Count; // finds the count for a specific level of the array --> (1)
      
              int getInt = ItemList[1].ElementAt(0).Item1; // finds int value --> (5)
              Point getPoint = ItemList[1].ElementAt(0).Item2; // finds the point --> (1,2)
      

      【讨论】:

        猜你喜欢
        • 2023-01-07
        • 2015-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多