3个变量的信息存储

本文关键字:存储 信息 变量 3个 | 更新日期: 2024-09-20 07:32:13

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

我想了一种方法,使用一系列字典

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

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

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个变量存储在一起会很好。

3个变量的信息存储

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

Tuple<int, int, Point>

要获取这些值,请使用相应的Item属性。对于第一个int,它将是yourTuple.Item1。对于第二个CCD_ 5和对于点CCD_。

如果你有多个Tuples,你可以使用一个经典的List来存储它们:

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

由于它是一个列表,您可以很容易地获得计数:tuples.Count()

所以class对我来说似乎是合适的结构。

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

然后将这些对象存储在List<>

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个值的元组,我只需要一个数组来表示一个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)