2010-12-29 25 views
11

Tôi muốn lưu trữ nhiều giá trị trong khóa duy nhất như:Hashtable với mutiple giá trị cho đơn chính

HashTable obj = new HashTable(); 
obj.Add("1", "test"); 
obj.Add("1", "Test1"); 

Ngay bây giờ này ném một lỗi.

+1

Nếu phím số sử dụng 'int' như chìa khóa, không phải' chuỗi', nếu có. – abatishchev

+0

Câu hỏi này là bản sao của http://stackoverflow.com/questions/2478567 và http://stackoverflow.com/questions/4454075 –

Trả lời

1

Bạn có thể sử dụng từ điển.

Thực ra, những gì bạn vừa mô tả là một cách sử dụng lý tưởng cho bộ sưu tập Từ điển. Nó có nghĩa vụ phải chứa các cặp khóa: giá trị, bất kể loại giá trị. Bằng cách biến giá trị thành lớp riêng của nó, bạn sẽ có thể mở rộng nó dễ dàng trong tương lai, nếu cần.

Mẫu mã:

class MappedValue 
{ 
    public string SomeString { get; set; } 
    public bool SomeBool { get; set; } 
} 

Dictionary<string, MappedValue> myList = new Dictionary<string, MappedValue>; 
+1

Nếu OP có thể sử dụng .NET 4.0 thì anh ta cũng có thể chỉ sử dụng 'Tuble ', v.v. – abatishchev

0

cửa hàng một danh sách trong hashtable:

obj.Add("1",new List<string>()); 
(obj["1"] as List<string>).Add("test"); 
(obj["1"] as List<string>).Add("test1"); 

Đây là một thủ thuật thông thường.

+0

Nếu bạn chắc chắn trong loại kết quả thì sử dụng' cast', chứ không phải toán tử 'as'. Và anyway - sử dụng bộ sưu tập chung chung, không .NET 1.x không chung chung. – abatishchev

1

Điều đó gây ra lỗi vì bạn đang thêm cùng một khóa hai lần. Thử sử dụng Dictionary thay vì HashTable.

Dictionary<int, IList<string>> values = new Dictionary<int, IList<string>>(); 
IList<string> list = new List<string>() 
{ 
    "test", "Test1" 
}; 
values.Add(1, list); 
+0

'IList' dành cho lưu trữ động + nhận theo chỉ mục. Chỉ để lưu trữ động là 'ICollection , phải không? – abatishchev

+0

Chắc chắn, phụ thuộc vào những gì anh ta muốn, anh ta có thể sử dụng 'IEnumerable', 'ICollection',' IList', 'string []' ... bất cứ điều gì anh ta cần – hunter

6

Bạn không thể sử dụng cùng một khóa trong Từ điển/Hashtable. Tôi nghĩ rằng bạn muốn sử dụng một danh sách cho mỗi chìa khóa, ví dụ (VB.NET):

Dim dic As New Dictionary(Of String, List(Of String)) 
Dim myValues As New List(Of String) 
myValues.Add("test") 
myValues.Add("Test1") 
dic.Add("1", myValues) 

C#:

Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>(); 
List<string> myValues = new List<string>(); 
myValues.Add("test"); 
myValues.Add("Test1"); 
dic.Add("1", myValues); 
0

Bạn đang tìm kiếm một Lookup, mà tự nhiên có thể lưu trữ nhiều giá trị cho mỗi khóa.

Như đã chỉ ra điều này chỉ hoạt động cho một danh sách cố định vì bạn không thể thêm mục nhập vào tra cứu khi bạn đã tạo nó.

public class LookupEntry 
{ 
    public string Key { get; set; } 
    public string Value { get; set; } 
} 

var list = new List<LookupEntry>(new LookupEntry [] 
            { 
            new LookupEntry() {Key="1", Value="Car" }, 
            new LookupEntry() {Key="1", Value="Truck"}, 
            new LookupEntry() {Key="2", Value="Duck"} 
            }); 


var lookup = list.ToLookup(x => x.Key, x => x.Value); 
var all1s = lookup["1"].ToList(); 
+1

'Lookup' là bất biến. Điều đó có thể tốt đẹp, nhưng có thể không hoạt động trong kịch bản OPs. – CodesInChaos

4

Tôi đang sử dụng lớp học MultiDictionary của riêng mình. Nó dựa trên một Dictionary<TKey,List<TValue>> nhưng cung cấp một chút đường cú pháp trên đầu trang của điều đó. Nên dễ đến mức độ Entry<TValue> để thực hiện IList<T>

public class MultiDictionary<TKey, TValue> 
{ 
    private Dictionary<TKey, List<TValue>> data = new Dictionary<TKey, List<TValue>>(); 

    public struct Entry : IEnumerable<TValue> 
    { 
     private readonly MultiDictionary<TKey, TValue> mDictionary; 
     private readonly TKey mKey; 

     public TKey Key { get { return mKey; } } 

     public bool IsEmpty 
     { 
      get 
      { 
       return !mDictionary.data.ContainsKey(Key); 
      } 
     } 

     public void Add(TValue value) 
     { 
      List<TValue> list; 
      if (!mDictionary.data.TryGetValue(Key, out list)) 
       list = new List<TValue>(); 
      list.Add(value); 
      mDictionary.data[Key] = list; 
     } 

     public bool Remove(TValue value) 
     { 
      List<TValue> list; 
      if (!mDictionary.data.TryGetValue(Key, out list)) 
       return false; 
      bool result = list.Remove(value); 
      if (list.Count == 0) 
       mDictionary.data.Remove(Key); 
      return result; 
     } 

     public void Clear() 
     { 
      mDictionary.data.Remove(Key); 
     } 

     internal Entry(MultiDictionary<TKey, TValue> dictionary, TKey key) 
     { 
      mDictionary = dictionary; 
      mKey = key; 
     } 

     public IEnumerator<TValue> GetEnumerator() 
     { 
      List<TValue> list; 
      if (!mDictionary.data.TryGetValue(Key, out list)) 
       return Enumerable.Empty<TValue>().GetEnumerator(); 
      else 
       return list.GetEnumerator(); 
     } 
     System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 
     { 
      return GetEnumerator(); 
     } 
    } 

    public Entry this[TKey key] 
    { 
     get 
     { 
      return new Entry(this, key); 
     } 
    } 
} 
0

JFYI, bạn có thể khai dic cách này của bạn:

Dictionary<int, IList<string>> dic = new 
{ 
    { 1, new List<string> { "Test1", "test1" }, 
    { 2, new List<string> { "Test2", "test2" } 
}; 
7

bạn có thể đặt test,test1,test2,... của bạn trong một bảng và sau đó đưa bảng này trong một Hashtable như một giá trị cho khóa sẽ giống nhau cho tất cả chúng.

Ví dụ thử một cái gì đó như thế này:

List<string> list = new List<string>(); 
list.Add("test"); 
list.Add("test1"); 

và sau đó:

HashTable obj = new HashTable(); 
obj.Add("1", list); 
0

Bạn có thể sử dụng NameValueCollection - hoạt động giống như Hashtable và có "GetValues ​​()".

0

Nó sẽ là tốt hơn cho bạn để sử dụng hai hashtables như tôi đã sử dụng trong this library

1

Có lẽ đó là 4 năm sau đó, nhưng tôi hy vọng nó sẽ giúp ai đó sau này. Như đã đề cập trước đó trong bài đăng, đó là không thể để sử dụng cùng một khóa cho giá trị khác nhau trong Hashtable (khóa, giá trị). Mặc dù, bạn có thể tạo Danh sách hoặc một số đối tượng làm giá trị trong cặp khóa/giá trị của HashTable.

//instantiate new Hashtable 
Hashtable hashtable = new Hashtable(); 

//create a class that would represent a value in the HashTable 
public class SomeObject 
{ 
    public string value1 { get; set;} 
    public string value2 { get; set;} 
} 

//create a List that would store our objects 
List<SomeObject> list = new List<someObject>(); 

//add new items to the created list 
list.Add(new SomeObject() 
      { 
       value1 = "test", 
       value2 = "test1" 
      }); 
list.Add(new SomeObject() 
      { 
       value1 = "secondObject_value1" 
       value2 = "secondObject_value2" 
      }) 

//add key/value pairs to the Hashtable. 
hashTable.Add("1", list[0]); 
hashTable.Add("2", list[1]); 

Sau đó để lấy dữ liệu này:

//retrieve the value for the key "1" 
SomeObject firstObj = (SomeObject)hashTable[1]; 
//retrieve the value for the key "2" 
SomeObject secondObj = (SomeObject)hashTable[2]; 
Console.WriteLine("Values of the first object are: {0} and {1}", 
              firstObj.value1,firstObj.value2); 
Console.WriteLine("Values of the second object are {0} and {1}", 
              secondObj.value1, secondObj.value2); 
// output for the WriteLine: 
Values of the first object are: test and test1 
Values of the second object are secondObject_value1 and secondObject_value2 
Các vấn đề liên quan