2017-02-13 15 views
0

如何在C#中存儲和檢索列表中的值?我可以存儲這樣的值如何使用列表<Hashtable>來自c#

List<Hashtable> mList=new List<Hashtable>(); 
Hashtable ht = new Hashtable(); 
ht.Add(1, "One"); 
ht.Add(2, "Two"); 
ht.Add(3, "Three"); 
ht.Add(4, "Four"); 
mList.Add(ht); 

如何將這些值設置爲在C#中的base adapter textview?

+1

我不知道Xamarin的textview,但將舊樣式的散列表放在'List <>中看起來很奇怪。你確定你需要這個嗎? –

+0

感謝buddy.Yes我需要和告訴我舊的風格也。我想用鍵存儲多個值 – Android1

回答

1

如何將這些值設置爲C#中的base adapter textview?

我假設你的基地適配器意味着BaseAdapterListView,那麼你可以從BaseAdapter創建一個適配器繼承例子是這樣的:

public class MainAdapter : BaseAdapter<Hashtable> 
{ 
    private List<Hashtable> items; 
    private Activity context; 

    public MainAdapter(Activity context, List<Hashtable> items) : base() 
    { 
     this.context = context; 
     this.items = items; 
    } 

    public override Hashtable this[int position] 
    { 
     get 
     { 
      return items[position]; 
     } 
    } 

    public override int Count 
    { 
     get 
     { 
      return items.Count; 
     } 
    } 

    public override long GetItemId(int position) 
    { 
     return position; 
    } 

    public override View GetView(int position, View convertView, ViewGroup parent) 
    { 
     View view = convertView; 
     if (view == null) 
      view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null); 
     view.FindViewById<TextView>(Android.Resource.Id.Text1).Text = items[position].ToString(); 
     return view; 
    } 
} 

,並使用List<HashTable>您的適配器是這樣的:

public class MainActivity : ListActivity 
{ 
    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate(bundle); 

     // Set our view from the "main" layout resource 
     //SetContentView(Resource.Layout.Main); 

     List<Hashtable> mList = new List<Hashtable>(); 
     Hashtable ht = new Hashtable(); 
     ht.Put(1, "One"); 
     ht.Put(2, "Two"); 
     ht.Put(3, "Three"); 
     ht.Put(4, "Four"); 
     mList.Add(ht); 

     ListAdapter = new MainAdapter(this, mList); 
    } 
} 

但我懷疑這真的是你需要的。您在List<>中只有一個項目,此項目有一個Hashtable,其中包含四個密鑰對值。您是否可能需要在每個項目ListView上顯示密鑰對值,而不是在一個項目中顯示四個密鑰對值?

我與@Henk Holterman同意,這是很奇怪的把一個老式的哈希表中List<>,如果你想使用List<>存儲與關鍵多個字符串值,你可以簡單地這樣的代碼:

List<string> mList = new List<string>(); 
mList.Add("One"); 
mList.Add("Two"); 
mList.Add("Three"); 
mList.Add("Four"); 

List<>本身分配的每一項指標,例如,如果你想找到字符串項目「三」的指標,你可以像這樣的代碼:

var index = mList.IndexOf("Three"); 

List<>中的第一項將匹配索引0,這裏的項目「三」的索引將是2.

當然,我不是說不允許將Hashtable存儲到List<>,但通常當我們想要定義一個Key for每一個項目,一個方法是創建一個類的模型,例如:

public class MyListModel 
{ 
    public int Key { get; set; } 
    public string Content { get; set; } 
} 

現在你可以爲這個模型創建一個List<>

List<MyListModel> mList = new List<MyListModel>(); 
for (int i = 1; i <= 10; i++) 
{ 
    mList.Add(new MyListModel { Key = i, Content = "item " + i }); 
} 

使用一個數據模型ListView是優勢如果你的每個ListView項目有例如多個TextView,每個用於顯示不同的信息,那麼你可以簡單地在這個類模型中添加這些屬性。

有關在Xamarin.Android中構建ListView的更多信息,請參閱ListViews and Adapters