Reputation: 47945
I need a Pair list, with "string", "string".
Tried :
Dictionary<string, string> Categories= new Dictionary<string, string>();
but can't add "700", "2" and "700", "3". I need a Pair where I can add everythings, when I want. Like a Vector that can contain N Vector (string, string). Which structure I need? Quickly, because I need to compaire them in LINQ, after :
myStructs = from MyObject s in MyObjects
join c in Categories on s.IDCategory.UniqueID equals c.Key
join d in Categories on s.Stars equals d.Value
select s;
Upvotes: 1
Views: 283
Reputation: 64467
Try List<Tuple<string, string>>
, or for increased readability, simply make a new type.
If you need it to make sense during linq, you could transfer the tuple into an anonymous type (using let
here) to give the type some sensible property names:
var items = new List<Tuple<string, string>>
{
new Tuple<string, string>("Adam", "1"),
new Tuple<string, string>("Adam", "2")
};
var names = from i in items
let person = new { Name = i.Item1, Number = i.Item2 }
select person.Name;
Makes it a little more readable during a linq query.
It the type is used a lot, I advise creating your own type with better property names for clarity as in Servy's answer. In the long run, Tuple<string, int, bool>
is a lot less obvious than:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool LikesCake { get; set; }
}
Tuple equality is based on the equality of all it's properties against an instance of the same type of tuple. For example, new Tuple("Adam", "1").Equals(new Tuple("Adam", "1"))
will be true.
Lists also do not stop duplicate items. If you need to enforce uniqueness across all the properties, then HashSet<Tuple<string, string>>
is what you need.
Upvotes: 9
Reputation: 647
A List<KeyValuePair<string, string>>
would probably work well if you're in .NET 3.5 or below, and if 4 or above, List<Tuple<string, string>>
would be a winner.
Upvotes: 0
Reputation: 203804
Just create your own.
public class Pair
{
public string First {get;set;}
public string Second {get;set;}
}
Then you can have a List<Pair>
to hold your data.
There are several possible library classes that you could re-purpose for your own needs, but in particular if this pair actually represents something (meaning you'd rename the class and the properties to something more meaningful) then it can be useful to have it in its own class to denote that. If you did want to just re-use an existing type then Tuple<string,string>
would probably be the best choice.
Upvotes: 4
Reputation: 9752
A Dictionary
is a hashed location keys, so you cannot have duplicates in the dictionary. You could have a list of type <string,string>
either by using aKeyValuePair
or Tuple
Upvotes: 0