0

我想要一个可以容纳整数和字符的数据类型。

private Int32[] XCordinates = {0,1,2,3,4,5,6,7,8,9 };
private Char[] yCordinates = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };

我想要这样的结果

A0
A1
A2
A3
A4 and so on.... upto 
J8
J9

现在我应该使用哪种数据类型来获得最快的性能和数据检索,让我们说“H6”条目。

  1. 字典是不等式的,因为它们不允许多个键

  2. 可以使用 ArrayList,但它只能存储一种类型的对象和所需的装箱/拆箱。

或者我可以使用

List<KeyValuePair<Char, Int32>> myKVPList = new List<KeyValuePair<Char, Int32>>();
foreach (Char yValue in yCordinates)
{
   foreach (Int32 xValue in XCordinates)
   {
       myKVPList.Add(new KeyValuePair<Char, Int32>(yValue, xValue));
    }
 }

但是与数组相比,List 在访问数据方面最慢,有什么建议吗?

4

2 回答 2

1

.NET 框架 3.5 包含一个特殊的 LINQLookup类。

var lookup = (from x in yCordinates
             from y in XCordinates
             select new{x, y}).ToLookup(xy => xy.x, xy => xy.y);

foreach(var xy in lookup)
    Console.WriteLine("x:{0} y-values:{1}", xy.Key, string.Join(",", xy.Select(y => y)));

结果:

x:A y-values:0,1,2,3,4,5,6,7,8,9
x:B y-values:0,1,2,3,4,5,6,7,8,9
x:C y-values:0,1,2,3,4,5,6,7,8,9
x:D y-values:0,1,2,3,4,5,6,7,8,9
x:E y-values:0,1,2,3,4,5,6,7,8,9
x:F y-values:0,1,2,3,4,5,6,7,8,9
x:G y-values:0,1,2,3,4,5,6,7,8,9
x:H y-values:0,1,2,3,4,5,6,7,8,9
x:I y-values:0,1,2,3,4,5,6,7,8,9
x:J y-values:0,1,2,3,4,5,6,7,8,9

ALookup<TKey, TElement>类似于 a Dictionary<TKey, TValue>。不同之处在于 aDictionary<TKey, TValue>将键映射到单个值,而 aLookup<TKey, TElement>将键映射到值的集合。

它的缺点是:

  • 您不能只创建一个 Lookup 对象,因为没有公共构造函数,它只能使用该.ToLookup方法
  • 一旦创建,您就无法对其进行编辑,也无法添加或删除等。

作为旁注,您可以在不存在的键上查询查找(通过索引器),您将获得一个空序列。对字典做同样的事情,你会得到一个例外。

于 2013-07-09T12:53:26.383 回答
0

您可以尝试字符和数字的字节表示,然后对其进行格式化:

        //values from 48-57 are 0 to 9,65-90 uppercase letters,97-122 lowercase letters
        byte[] ba = new byte[] { 65, 49, 70, 52, 88, 55 };

        for (int i = 0; i < ba.Length; i += 2)
        {
            Console.WriteLine(string.Format("{0}{1}",(char)ba[i],(char)ba[i + 1]));
        }

        Console.ReadKey();

如果你真的不想使用字典,你也可以尝试字符串表示:

            string[] vals = new string[] { "A122", "C67", "T8" };
            foreach (var item in vals)
            {
                //this is just to show you can convert to an int because if its
                //one letter and numbers you know index 1 of string will be
                //the start of the number representation.
                int count = int.Parse(item.Substring(1, item.Length - 1));
                Console.WriteLine("{0},{1}", item.Substring(0, 1), item.Substring(1, item.Length - 1));
            }
于 2013-07-09T12:58:02.383 回答