我想要一个可以容纳整数和字符的数据类型。
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
现在我应该使用哪种数据类型来获得最快的性能和数据检索。让Say“H6”条目。
字典不合规,因为它们不允许使用多个键
可以使用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访问数据的速度最慢,有什么建议吗?
答案 0 :(得分:1)
.NET framework 3.5包含一个特殊的LINQ Lookup
类。
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
Lookup<TKey, TElement>
类似于Dictionary<TKey, TValue>
。区别在于Dictionary<TKey, TValue>
将键映射到单个值,而Lookup<TKey, TElement>
将键映射到值集合。
它的缺点是:
.ToLookup
方法作为旁注,您可以在不存在的键上查询(通过索引器),并且您将获得一个空序列。用字典做同样的事情,你会得到一个例外。
答案 1 :(得分: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));
}