Reputation: 2744
I want an datatype which can hold an Integer and Char.
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' };
and I want result something like this
A0
A1
A2
A3
A4 and so on.... upto
J8
J9
Now which data type should I use for the fastest performance and data retrieval from lets Say "H6" entry.
Dictionaries are out of equation since they don't allow multiple keys
ArrayList could be used but it can store only one type of object and required boxing/unboxing.
or I can use
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));
}
}
but List are slowest in accessing data as compared to arrays, Any suggestions ?
Upvotes: 0
Views: 259
Reputation: 4542
you can try the byte representation of characters and numbers then formatt them:
//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();
If you really dont want to use dictionary you can also try just string representation:
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));
}
Upvotes: 0
Reputation: 460028
The .NET framework 3.5 includes a special LINQ Lookup
class.
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)));
Result:
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
A Lookup<TKey, TElement>
is similar to a Dictionary<TKey, TValue>
. The difference is that a Dictionary<TKey, TValue>
maps keys to single values, whereas a Lookup<TKey, TElement>
maps keys to collections of values.
It's drawbacks are:
.ToLookup
methodAs a side note, you can query a lookup (via the indexer) on a key that doesn't exist, and you'll get an empty sequence. Do the same with a dictionary and you'll get an exception.
Upvotes: 1