简体   繁体   中英

ASP.NET which type of collection should I use?

I am writing a class to save searches on my site. I want to have in the class an "Array" of all the parameters that were specified. I tried a NameValueCollection but the problem I ran into is when I have a multi-select (eg states) it only stores one of the entries because the key gets taken. I need a collection type that will let me have something like the following:

Name => Bob
State => Alaska
State => Oregon
State => Washington
Company => Acme

What type of collection should I use?

EDIT: ==============================

I'm not sure the comments so far will help. Let me explain a little further. This search class will be used to save the parameters for any search on my site. Different searches may or may not have the same parameters. When this classes save method is called the search will be dumped into a database. One record will be created in the Searches table and as many records an there are items in the collection will be created in the SearchesParameters table. The SearchesParamaters table has these columns (ID,searches_ID,key,value).

The database could care less if there are two parameters with a key of "State". In order to keep my class generic enough to use on all searches without having to be updated I want to have a collection/array that will let me have key/value pairs and also let me have multiple instances of the same key. Really I just want to be able to call searchObj.addParameter(KEY,VALUE); How the class handles that on the back end is mostly irrelevant so long as i can reliably get the correct keys paired up with the correct values.

Is a collection the way to go with this or should I be considering something like two arrays one storing the keys and one storing the values?

A Dictionary that maps String to an List<string> . Something like Dictionary<string, List<string>> .

If an element isn't there in the Dictionary, create a new List for the Key and add to it. Otherwise, simply add the new Value to the existing List.

Create a class, and store that class in a collection.

class Search
{
  public string Name { get; set; }
  public List<string> State { get; set; }
  public string Company { get; set; }
}

Then you can have multiple states per search. Add instances of this to List and away you to.

what about a generic list (System.Collections.Generic)?

eg,

string name;
List<string> states;
string company;

You can read up about generic lists here

您应该使用List<KeyValuePair<string, string>>

我会使用Dictionary<string, HashSet<string>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM