Roy*_*son 11 .net c# dictionary
我想将值存储为键,值,值对.我的数据类型
Key -> int & both values -> ulong,
Run Code Online (Sandbox Code Playgroud)
如何初始化和获取此类字典的值.我正在使用VS-2005.
如果我使用类或结构,那么我如何获取值.
bni*_*dyc 17
创建一个存储值的结构:
struct ValuePair
{
public ulong Value1;
public ulong Value2;
}
Run Code Online (Sandbox Code Playgroud)
字典初始化:
Dictionary<int, ValuePair> dictionary = new Dictionary<int, ValuePair>();
Run Code Online (Sandbox Code Playgroud)
如果你使用int作为密钥,也许List就足够了?
列表:
List<ValuePair> list = new List<ValuePair>();
Run Code Online (Sandbox Code Playgroud)
ValuePair可以添加到list以下内容:
list.Add(new ValuePair { Value1 = 1, Value2 = 2 });
Run Code Online (Sandbox Code Playgroud)
Kon*_*man 14
您可以声明一个存储两个值的类,然后使用普通字典.例如:
class Values {
ulong Value1 {get;set;}
ulong Value2 {get;set;}
}
var theDictionary=new Dictionary<int, Values>;
theDictionary.Add(1, new Values {Value1=2, Value2=3});
Run Code Online (Sandbox Code Playgroud)
这是一个选择:
Dictionary<int, KeyValuePair<ulong, ulong>> dictionary = new Dictionary<int, KeyValuePair<ulong, ulong>>();
Run Code Online (Sandbox Code Playgroud)
如果要添加值:Key = 1,Pair = {2,3}
dictionary.Add(1, new KeyValuePair<ulong, ulong>(2, 3));
Run Code Online (Sandbox Code Playgroud)
如果要检索这些值:
var valuePair = dictionary[1];
ulong value1 = valuePair.Key;
ulong value2 = valuePair.Value;
Run Code Online (Sandbox Code Playgroud)
或者干脆:
ulong value1 = dictionary[1].Key;
Run Code Online (Sandbox Code Playgroud)
在System命名空间中创建一个Tuple类:
public class Tuple<T1,T2>
{
private readonly T1 _item1;
private readonly T2 _item2;
public Tuple(T1 item1, T2 item2)
{
this._item1 = item1;
this._item2 = item2;
}
public T1 Item1 { get { return _item1; } }
public T2 Item2 { get { return _item2; } }
}
Run Code Online (Sandbox Code Playgroud)
还有一个带有Create方法的静态Tuple类,因此您可以获得构造函数中不可用的类型推断:
public static class Tuple
{
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
{
return new Tuple<T1, T2>(item1, item2);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当你进入.NET 4.0时,你可以删除这些类,因为它们在基类库中(并且与F#元组兼容!).
| 归档时间: |
|
| 查看次数: |
49500 次 |
| 最近记录: |